47 #include "compiler/compileBroker.hpp"
48 #include "gc/shared/collectedHeap.inline.hpp"
49 #include "interpreter/bytecodeStream.hpp"
50 #include "interpreter/oopMapCache.hpp"
51 #include "interpreter/rewriter.hpp"
52 #include "jvm.h"
53 #include "jvmtifiles/jvmti.h"
54 #include "klass.inline.hpp"
55 #include "logging/log.hpp"
56 #include "logging/logMessage.hpp"
57 #include "logging/logStream.hpp"
58 #include "memory/allocation.inline.hpp"
59 #include "memory/iterator.inline.hpp"
60 #include "memory/metadataFactory.hpp"
61 #include "memory/metaspaceClosure.hpp"
62 #include "memory/oopFactory.hpp"
63 #include "memory/resourceArea.hpp"
64 #include "memory/universe.hpp"
65 #include "oops/constantPool.hpp"
66 #include "oops/fieldStreams.inline.hpp"
67 #include "oops/instanceClassLoaderKlass.hpp"
68 #include "oops/instanceKlass.inline.hpp"
69 #include "oops/instanceMirrorKlass.hpp"
70 #include "oops/instanceOop.hpp"
71 #include "oops/instanceStackChunkKlass.hpp"
72 #include "oops/klass.inline.hpp"
73 #include "oops/method.hpp"
74 #include "oops/oop.inline.hpp"
75 #include "oops/recordComponent.hpp"
76 #include "oops/symbol.hpp"
77 #include "prims/jvmtiExport.hpp"
78 #include "prims/jvmtiRedefineClasses.hpp"
79 #include "prims/jvmtiThreadState.hpp"
80 #include "prims/methodComparator.hpp"
81 #include "runtime/arguments.hpp"
82 #include "runtime/atomicAccess.hpp"
83 #include "runtime/deoptimization.hpp"
84 #include "runtime/fieldDescriptor.inline.hpp"
85 #include "runtime/handles.inline.hpp"
86 #include "runtime/javaCalls.hpp"
87 #include "runtime/javaThread.inline.hpp"
88 #include "runtime/mutexLocker.hpp"
89 #include "runtime/orderAccess.hpp"
90 #include "runtime/os.inline.hpp"
91 #include "runtime/reflection.hpp"
92 #include "runtime/synchronizer.hpp"
93 #include "runtime/threads.hpp"
94 #include "services/classLoadingService.hpp"
95 #include "services/finalizerService.hpp"
96 #include "services/threadService.hpp"
97 #include "utilities/dtrace.hpp"
98 #include "utilities/events.hpp"
99 #include "utilities/macros.hpp"
100 #include "utilities/nativeStackPrinter.hpp"
101 #include "utilities/stringUtils.hpp"
102 #ifdef COMPILER1
103 #include "c1/c1_Compiler.hpp"
104 #endif
105 #if INCLUDE_JFR
106 #include "jfr/jfrEvents.hpp"
107 #endif
108
109 #ifdef DTRACE_ENABLED
110
111
112 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
113 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
114 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
115 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
116 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
117 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
118 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
119 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
120 #define DTRACE_CLASSINIT_PROBE(type, thread_type) \
133 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait) \
134 { \
135 char* data = nullptr; \
136 int len = 0; \
137 Symbol* clss_name = name(); \
138 if (clss_name != nullptr) { \
139 data = (char*)clss_name->bytes(); \
140 len = clss_name->utf8_length(); \
141 } \
142 HOTSPOT_CLASS_INITIALIZATION_##type( \
143 data, len, (void*)class_loader(), thread_type, wait); \
144 }
145
146 #else // ndef DTRACE_ENABLED
147
148 #define DTRACE_CLASSINIT_PROBE(type, thread_type)
149 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)
150
151 #endif // ndef DTRACE_ENABLED
152
153 bool InstanceKlass::_finalization_enabled = true;
154 static int call_class_initializer_counter = 0; // for debugging
155
156 static inline bool is_class_loader(const Symbol* class_name,
157 const ClassFileParser& parser) {
158 assert(class_name != nullptr, "invariant");
159
160 if (class_name == vmSymbols::java_lang_ClassLoader()) {
161 return true;
162 }
163
164 if (vmClasses::ClassLoader_klass_is_loaded()) {
165 const Klass* const super_klass = parser.super_klass();
166 if (super_klass != nullptr) {
167 if (super_klass->is_subtype_of(vmClasses::ClassLoader_klass())) {
168 return true;
169 }
170 }
171 }
172 return false;
173 }
174
175 static inline bool is_stack_chunk_class(const Symbol* class_name,
176 const ClassLoaderData* loader_data) {
177 return (class_name == vmSymbols::jdk_internal_vm_StackChunk() &&
178 loader_data->is_the_null_class_loader_data());
179 }
180
181 // private: called to verify that k is a static member of this nest.
182 // We know that k is an instance class in the same package and hence the
183 // same classloader.
184 bool InstanceKlass::has_nest_member(JavaThread* current, InstanceKlass* k) const {
185 assert(!is_hidden(), "unexpected hidden class");
186 if (_nest_members == nullptr || _nest_members == Universe::the_empty_short_array()) {
187 if (log_is_enabled(Trace, class, nestmates)) {
188 ResourceMark rm(current);
189 log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
190 k->external_name(), this->external_name());
191 }
192 return false;
193 }
194
442 log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
443 this->external_name(),
444 access ? "" : "NOT ",
445 k->external_name());
446 return access;
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 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
459 const int size = InstanceKlass::size(parser.vtable_size(),
460 parser.itable_size(),
461 nonstatic_oop_map_size(parser.total_oop_map_count()),
462 parser.is_interface());
463
464 const Symbol* const class_name = parser.class_name();
465 assert(class_name != nullptr, "invariant");
466 ClassLoaderData* loader_data = parser.loader_data();
467 assert(loader_data != nullptr, "invariant");
468
469 InstanceKlass* ik;
470
471 // Allocation
472 if (parser.is_instance_ref_klass()) {
473 // java.lang.ref.Reference
474 ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
475 } else if (class_name == vmSymbols::java_lang_Class()) {
476 // mirror - java.lang.Class
477 ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
478 } else if (is_stack_chunk_class(class_name, loader_data)) {
479 // stack chunk
480 ik = new (loader_data, size, THREAD) InstanceStackChunkKlass(parser);
481 } else if (is_class_loader(class_name, parser)) {
482 // class loader - java.lang.ClassLoader
483 ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);
484 } else {
485 // normal
486 ik = new (loader_data, size, THREAD) InstanceKlass(parser);
487 }
488
489 assert(ik == nullptr || CompressedKlassPointers::is_encodable(ik),
490 "Klass " PTR_FORMAT "needs a narrow Klass ID, but is not encodable", p2i(ik));
491
492 // Check for pending exception before adding to the loader data and incrementing
493 // class count. Can get OOM here.
494 if (HAS_PENDING_EXCEPTION) {
495 return nullptr;
496 }
497
498 return ik;
499 }
500
501
502 // copy method ordering from resource area to Metaspace
503 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
504 if (m != nullptr) {
505 // allocate a new array and copy contents (memcpy?)
506 _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
507 for (int i = 0; i < m->length(); i++) {
508 _method_ordering->at_put(i, m->at(i));
509 }
510 } else {
511 _method_ordering = Universe::the_empty_int_array();
512 }
513 }
514
515 // create a new array of vtable_indices for default methods
516 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
517 Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
518 assert(default_vtable_indices() == nullptr, "only create once");
519 set_default_vtable_indices(vtable_indices);
520 return vtable_indices;
521 }
522
523
524 InstanceKlass::InstanceKlass() {
525 assert(CDSConfig::is_dumping_static_archive() || CDSConfig::is_using_archive(), "only for CDS");
526 }
527
528 InstanceKlass::InstanceKlass(const ClassFileParser& parser, KlassKind kind, ReferenceType reference_type) :
529 Klass(kind),
530 _nest_members(nullptr),
531 _nest_host(nullptr),
532 _permitted_subclasses(nullptr),
533 _record_components(nullptr),
534 _static_field_size(parser.static_field_size()),
535 _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
536 _itable_len(parser.itable_size()),
537 _nest_host_index(0),
538 _init_state(allocated),
539 _reference_type(reference_type),
540 _init_thread(nullptr)
541 {
542 set_vtable_length(parser.vtable_size());
543 set_access_flags(parser.access_flags());
544 if (parser.is_hidden()) set_is_hidden();
545 set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
546 false));
547
548 assert(nullptr == _methods, "underlying memory not zeroed?");
549 assert(is_instance_klass(), "is layout incorrect?");
550 assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
551 }
552
553 void InstanceKlass::set_is_cloneable() {
554 if (name() == vmSymbols::java_lang_invoke_MemberName()) {
555 assert(is_final(), "no subclasses allowed");
556 // MemberName cloning should not be intrinsified and always happen in JVM_Clone.
557 } else if (reference_type() != REF_NONE) {
558 // Reference cloning should not be intrinsified and always happen in JVM_Clone.
559 } else {
560 set_is_cloneable_fast();
561 }
562 }
563
564 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
565 Array<Method*>* methods) {
566 if (methods != nullptr && methods != Universe::the_empty_method_array() &&
682
683 deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
684 set_transitive_interfaces(nullptr);
685 set_local_interfaces(nullptr);
686
687 if (fieldinfo_stream() != nullptr && !fieldinfo_stream()->in_aot_cache()) {
688 MetadataFactory::free_array<u1>(loader_data, fieldinfo_stream());
689 }
690 set_fieldinfo_stream(nullptr);
691
692 if (fieldinfo_search_table() != nullptr && !fieldinfo_search_table()->in_aot_cache()) {
693 MetadataFactory::free_array<u1>(loader_data, fieldinfo_search_table());
694 }
695 set_fieldinfo_search_table(nullptr);
696
697 if (fields_status() != nullptr && !fields_status()->in_aot_cache()) {
698 MetadataFactory::free_array<FieldStatus>(loader_data, fields_status());
699 }
700 set_fields_status(nullptr);
701
702 // If a method from a redefined class is using this constant pool, don't
703 // delete it, yet. The new class's previous version will point to this.
704 if (constants() != nullptr) {
705 assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
706 if (!constants()->in_aot_cache()) {
707 HeapShared::remove_scratch_resolved_references(constants());
708 MetadataFactory::free_metadata(loader_data, constants());
709 }
710 // Delete any cached resolution errors for the constant pool
711 SystemDictionary::delete_resolution_error(constants());
712
713 set_constants(nullptr);
714 }
715
716 if (inner_classes() != nullptr &&
717 inner_classes() != Universe::the_empty_short_array() &&
718 !inner_classes()->in_aot_cache()) {
719 MetadataFactory::free_array<jushort>(loader_data, inner_classes());
720 }
721 set_inner_classes(nullptr);
722
723 if (nest_members() != nullptr &&
724 nest_members() != Universe::the_empty_short_array() &&
725 !nest_members()->in_aot_cache()) {
726 MetadataFactory::free_array<jushort>(loader_data, nest_members());
727 }
728 set_nest_members(nullptr);
729
730 if (permitted_subclasses() != nullptr &&
731 permitted_subclasses() != Universe::the_empty_short_array() &&
732 !permitted_subclasses()->in_aot_cache()) {
733 MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
734 }
735 set_permitted_subclasses(nullptr);
736
737 // We should deallocate the Annotations instance if it's not in shared spaces.
738 if (annotations() != nullptr && !annotations()->in_aot_cache()) {
739 MetadataFactory::free_metadata(loader_data, annotations());
740 }
741 set_annotations(nullptr);
742
743 SystemDictionaryShared::handle_class_unloading(this);
744
745 #if INCLUDE_CDS_JAVA_HEAP
746 if (CDSConfig::is_dumping_heap()) {
747 HeapShared::remove_scratch_objects(this);
748 }
749 #endif
750 }
751
752 bool InstanceKlass::is_record() const {
753 return _record_components != nullptr &&
754 is_final() &&
755 super() == vmClasses::Record_klass();
756 }
759 return _permitted_subclasses != nullptr &&
760 _permitted_subclasses != Universe::the_empty_short_array();
761 }
762
763 // JLS 8.9: An enum class is either implicitly final and derives
764 // from java.lang.Enum, or else is implicitly sealed to its
765 // anonymous subclasses. This query detects both kinds.
766 // It does not validate the finality or
767 // sealing conditions: it merely checks for a super of Enum.
768 // This is sufficient for recognizing well-formed enums.
769 bool InstanceKlass::is_enum_subclass() const {
770 InstanceKlass* s = super();
771 return (s == vmClasses::Enum_klass() ||
772 (s != nullptr && s->super() == vmClasses::Enum_klass()));
773 }
774
775 bool InstanceKlass::should_be_initialized() const {
776 return !is_initialized();
777 }
778
779 klassItable InstanceKlass::itable() const {
780 return klassItable(const_cast<InstanceKlass*>(this));
781 }
782
783 // JVMTI spec thinks there are signers and protection domain in the
784 // instanceKlass. These accessors pretend these fields are there.
785 // The hprof specification also thinks these fields are in InstanceKlass.
786 oop InstanceKlass::protection_domain() const {
787 // return the protection_domain from the mirror
788 return java_lang_Class::protection_domain(java_mirror());
789 }
790
791 objArrayOop InstanceKlass::signers() const {
792 // return the signers from the mirror
793 return java_lang_Class::signers(java_mirror());
794 }
795
796 oop InstanceKlass::init_lock() const {
797 // return the init lock from the mirror
798 oop lock = java_lang_Class::init_lock(java_mirror());
934 #ifdef ASSERT
935 {
936 Handle h_init_lock(THREAD, init_lock());
937 ObjectLocker ol(h_init_lock, THREAD);
938 assert(!is_initialized(), "sanity");
939 assert(!is_being_initialized(), "sanity");
940 assert(!is_in_error_state(), "sanity");
941 }
942 #endif
943
944 set_init_thread(THREAD);
945 set_initialization_state_and_notify(fully_initialized, CHECK);
946 }
947 #endif
948
949 bool InstanceKlass::verify_code(TRAPS) {
950 // 1) Verify the bytecodes
951 return Verifier::verify(this, should_verify_class(), THREAD);
952 }
953
954 void InstanceKlass::link_class(TRAPS) {
955 assert(is_loaded(), "must be loaded");
956 if (!is_linked()) {
957 link_class_impl(CHECK);
958 }
959 }
960
961 // Called to verify that a class can link during initialization, without
962 // throwing a VerifyError.
963 bool InstanceKlass::link_class_or_fail(TRAPS) {
964 assert(is_loaded(), "must be loaded");
965 if (!is_linked()) {
966 link_class_impl(CHECK_false);
967 }
968 return is_linked();
969 }
970
971 bool InstanceKlass::link_class_impl(TRAPS) {
972 if (CDSConfig::is_dumping_static_archive() && SystemDictionaryShared::has_class_failed_verification(this)) {
973 // This is for CDS static dump only -- we use the in_error_state to indicate that
1004 THREAD_AND_LOCATION,
1005 vmSymbols::java_lang_IncompatibleClassChangeError(),
1006 "class %s has interface %s as super class",
1007 external_name(),
1008 super_klass->external_name()
1009 );
1010 return false;
1011 }
1012
1013 super_klass->link_class_impl(CHECK_false);
1014 }
1015
1016 // link all interfaces implemented by this class before linking this class
1017 Array<InstanceKlass*>* interfaces = local_interfaces();
1018 int num_interfaces = interfaces->length();
1019 for (int index = 0; index < num_interfaces; index++) {
1020 InstanceKlass* interk = interfaces->at(index);
1021 interk->link_class_impl(CHECK_false);
1022 }
1023
1024 // in case the class is linked in the process of linking its superclasses
1025 if (is_linked()) {
1026 return true;
1027 }
1028
1029 // trace only the link time for this klass that includes
1030 // the verification time
1031 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
1032 ClassLoader::perf_class_link_selftime(),
1033 ClassLoader::perf_classes_linked(),
1034 jt->get_thread_stat()->perf_recursion_counts_addr(),
1035 jt->get_thread_stat()->perf_timers_addr(),
1036 PerfClassTraceTime::CLASS_LINK);
1037
1038 // verification & rewriting
1039 {
1040 HandleMark hm(THREAD);
1041 Handle h_init_lock(THREAD, init_lock());
1042 ObjectLocker ol(h_init_lock, CHECK_PREEMPTABLE_false);
1043 // Don't allow preemption if we link/initialize classes below,
1333 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1334 ss.as_string(), cause);
1335 }
1336 } else {
1337
1338 // Step 6
1339 set_init_state(being_initialized);
1340 set_init_thread(jt);
1341 if (debug_logging_enabled) {
1342 ResourceMark rm(jt);
1343 log_debug(class, init)("Thread \"%s\" is initializing %s",
1344 jt->name(), external_name());
1345 }
1346 }
1347 }
1348
1349 // Block preemption once we are the initializer thread. Unmounting now
1350 // would complicate the reentrant case (identity is platform thread).
1351 NoPreemptMark npm(THREAD);
1352
1353 // Step 7
1354 // Next, if C is a class rather than an interface, initialize it's super class and super
1355 // interfaces.
1356 if (!is_interface()) {
1357 Klass* super_klass = super();
1358 if (super_klass != nullptr && super_klass->should_be_initialized()) {
1359 super_klass->initialize(THREAD);
1360 }
1361 // If C implements any interface that declares a non-static, concrete method,
1362 // the initialization of C triggers initialization of its super interfaces.
1363 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1364 // having a superinterface that declares, non-static, concrete methods
1365 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1366 initialize_super_interfaces(THREAD);
1367 }
1368
1369 // If any exceptions, complete abruptly, throwing the same exception as above.
1370 if (HAS_PENDING_EXCEPTION) {
1371 Handle e(THREAD, PENDING_EXCEPTION);
1372 CLEAR_PENDING_EXCEPTION;
1386 // Step 8
1387 {
1388 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1389 if (class_initializer() != nullptr) {
1390 // Timer includes any side effects of class initialization (resolution,
1391 // etc), but not recursive entry into call_class_initializer().
1392 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1393 ClassLoader::perf_class_init_selftime(),
1394 ClassLoader::perf_classes_inited(),
1395 jt->get_thread_stat()->perf_recursion_counts_addr(),
1396 jt->get_thread_stat()->perf_timers_addr(),
1397 PerfClassTraceTime::CLASS_CLINIT);
1398 call_class_initializer(THREAD);
1399 } else {
1400 // The elapsed time is so small it's not worth counting.
1401 if (UsePerfData) {
1402 ClassLoader::perf_classes_inited()->inc();
1403 }
1404 call_class_initializer(THREAD);
1405 }
1406 }
1407
1408 // Step 9
1409 if (!HAS_PENDING_EXCEPTION) {
1410 set_initialization_state_and_notify(fully_initialized, CHECK);
1411 DEBUG_ONLY(vtable().verify(tty, true);)
1412 CompilationPolicy::replay_training_at_init(this, THREAD);
1413 }
1414 else {
1415 // Step 10 and 11
1416 Handle e(THREAD, PENDING_EXCEPTION);
1417 CLEAR_PENDING_EXCEPTION;
1418 // JVMTI has already reported the pending exception
1419 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1420 JvmtiExport::clear_detected_exception(jt);
1421 {
1422 EXCEPTION_MARK;
1423 add_initialization_error(THREAD, e);
1424 set_initialization_state_and_notify(initialization_error, THREAD);
1425 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1439 }
1440 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1441 }
1442
1443
1444 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1445 Handle h_init_lock(THREAD, init_lock());
1446 if (h_init_lock() != nullptr) {
1447 ObjectLocker ol(h_init_lock, THREAD);
1448 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1449 set_init_state(state);
1450 fence_and_clear_init_lock();
1451 ol.notify_all(CHECK);
1452 } else {
1453 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1454 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1455 set_init_state(state);
1456 }
1457 }
1458
1459 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1460 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1461 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1462 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1463
1464 DeoptimizationScope deopt_scope;
1465 {
1466 MutexLocker ml(current, Compile_lock);
1467
1468 set_init_state(InstanceKlass::loaded);
1469 // make sure init_state store is already done.
1470 // The compiler reads the hierarchy outside of the Compile_lock.
1471 // Access ordering is used to add to hierarchy.
1472
1473 // Link into hierarchy.
1474 append_to_sibling_list(); // add to superklass/sibling list
1475 process_interfaces(); // handle all "implements" declarations
1476
1477 // Now mark all code that depended on old class hierarchy.
1478 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1689 : vmSymbols::java_lang_IllegalAccessException(), external_name());
1690 }
1691 }
1692
1693 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
1694 // Need load-acquire for lock-free read
1695 if (array_klasses_acquire() == nullptr) {
1696
1697 // Recursively lock array allocation
1698 RecursiveLocker rl(MultiArray_lock, THREAD);
1699
1700 // Check if another thread created the array klass while we were waiting for the lock.
1701 if (array_klasses() == nullptr) {
1702 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
1703 // use 'release' to pair with lock-free load
1704 release_set_array_klasses(k);
1705 }
1706 }
1707
1708 // array_klasses() will always be set at this point
1709 ObjArrayKlass* ak = array_klasses();
1710 assert(ak != nullptr, "should be set");
1711 return ak->array_klass(n, THREAD);
1712 }
1713
1714 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1715 // Need load-acquire for lock-free read
1716 ObjArrayKlass* oak = array_klasses_acquire();
1717 if (oak == nullptr) {
1718 return nullptr;
1719 } else {
1720 return oak->array_klass_or_null(n);
1721 }
1722 }
1723
1724 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1725 return array_klass(1, THREAD);
1726 }
1727
1728 ArrayKlass* InstanceKlass::array_klass_or_null() {
1729 return array_klass_or_null(1);
1730 }
1731
1732 Method* InstanceKlass::class_initializer() const {
1733 Method* clinit = find_method(
1734 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1735 if (clinit != nullptr && clinit->has_valid_initializer_flags()) {
1736 return clinit;
1737 }
1738 return nullptr;
1739 }
1740
1741 void InstanceKlass::call_class_initializer(TRAPS) {
1742 if (ReplayCompiles &&
1743 (ReplaySuppressInitializers == 1 ||
1744 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1745 // Hide the existence of the initializer for the purpose of replaying the compile
1746 return;
1747 }
1748
1749 #if INCLUDE_CDS
1750 // This is needed to ensure the consistency of the archived heap objects.
1751 if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
1752 AOTClassInitializer::call_runtime_setup(THREAD, this);
1753 return;
1754 } else if (has_archived_enum_objs()) {
1755 assert(in_aot_cache(), "must be");
1824
1825 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1826 InterpreterOopMap* entry_for) {
1827 // Lazily create the _oop_map_cache at first request.
1828 // Load_acquire is needed to safely get instance published with CAS by another thread.
1829 OopMapCache* oop_map_cache = AtomicAccess::load_acquire(&_oop_map_cache);
1830 if (oop_map_cache == nullptr) {
1831 // Try to install new instance atomically.
1832 oop_map_cache = new OopMapCache();
1833 OopMapCache* other = AtomicAccess::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
1834 if (other != nullptr) {
1835 // Someone else managed to install before us, ditch local copy and use the existing one.
1836 delete oop_map_cache;
1837 oop_map_cache = other;
1838 }
1839 }
1840 // _oop_map_cache is constant after init; lookup below does its own locking.
1841 oop_map_cache->lookup(method, bci, entry_for);
1842 }
1843
1844 bool InstanceKlass::contains_field_offset(int offset) {
1845 fieldDescriptor fd;
1846 return find_field_from_offset(offset, false, &fd);
1847 }
1848
1849 FieldInfo InstanceKlass::field(int index) const {
1850 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
1851 if (fs.index() == index) {
1852 return fs.to_FieldInfo();
1853 }
1854 }
1855 fatal("Field not found");
1856 return FieldInfo();
1857 }
1858
1859 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1860 JavaFieldStream fs(this);
1861 if (fs.lookup(name, sig)) {
1862 assert(fs.name() == name, "name must match");
1863 assert(fs.signature() == sig, "signature must match");
1864 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
1865 return true;
1866 }
1867 return false;
1908
1909 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1910 // search order according to newest JVM spec (5.4.3.2, p.167).
1911 // 1) search for field in current klass
1912 if (find_local_field(name, sig, fd)) {
1913 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1914 }
1915 // 2) search for field recursively in direct superinterfaces
1916 if (is_static) {
1917 Klass* intf = find_interface_field(name, sig, fd);
1918 if (intf != nullptr) return intf;
1919 }
1920 // 3) apply field lookup recursively if superclass exists
1921 { InstanceKlass* supr = super();
1922 if (supr != nullptr) return supr->find_field(name, sig, is_static, fd);
1923 }
1924 // 4) otherwise field lookup fails
1925 return nullptr;
1926 }
1927
1928
1929 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1930 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1931 if (fs.offset() == offset) {
1932 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
1933 if (fd->is_static() == is_static) return true;
1934 }
1935 }
1936 return false;
1937 }
1938
1939
1940 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1941 const InstanceKlass* klass = this;
1942 while (klass != nullptr) {
1943 if (klass->find_local_field_from_offset(offset, is_static, fd)) {
1944 return true;
1945 }
1946 klass = klass->super();
1947 }
1948 return false;
1949 }
1950
1951
1952 void InstanceKlass::methods_do(void f(Method* method)) {
1953 // Methods aren't stable until they are loaded. This can be read outside
1954 // a lock through the ClassLoaderData for profiling
1955 // Redefined scratch classes are on the list and need to be cleaned
1956 if (!is_loaded() && !is_scratch_class()) {
1957 return;
1958 }
1959
1960 int len = methods()->length();
1961 for (int index = 0; index < len; index++) {
1962 Method* m = methods()->at(index);
1963 assert(m->is_method(), "must be method");
1964 f(m);
1965 }
1966 }
1967
1968
1969 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
1970 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1971 if (fs.access_flags().is_static()) {
1972 fieldDescriptor& fd = fs.field_descriptor();
1973 cl->do_field(&fd);
1974 }
1975 }
1976 }
1977
1978
1979 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
1980 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1981 if (fs.access_flags().is_static()) {
1982 fieldDescriptor& fd = fs.field_descriptor();
1983 f(&fd, mirror, CHECK);
1984 }
1985 }
1986 }
1987
1988 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
1989 InstanceKlass* super = this->super();
1990 if (super != nullptr) {
1991 super->do_nonstatic_fields(cl);
1992 }
1993 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1994 fieldDescriptor& fd = fs.field_descriptor();
1995 if (!fd.is_static()) {
1996 cl->do_field(&fd);
1997 }
1998 }
1999 }
2000
2291 }
2292
2293 // uncached_lookup_method searches both the local class methods array and all
2294 // superclasses methods arrays, skipping any overpass methods in superclasses,
2295 // and possibly skipping private methods.
2296 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2297 const Symbol* signature,
2298 OverpassLookupMode overpass_mode,
2299 PrivateLookupMode private_mode) const {
2300 OverpassLookupMode overpass_local_mode = overpass_mode;
2301 const InstanceKlass* klass = this;
2302 while (klass != nullptr) {
2303 Method* const method = klass->find_method_impl(name,
2304 signature,
2305 overpass_local_mode,
2306 StaticLookupMode::find,
2307 private_mode);
2308 if (method != nullptr) {
2309 return method;
2310 }
2311 klass = klass->super();
2312 overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses
2313 }
2314 return nullptr;
2315 }
2316
2317 #ifdef ASSERT
2318 // search through class hierarchy and return true if this class or
2319 // one of the superclasses was redefined
2320 bool InstanceKlass::has_redefined_this_or_super() const {
2321 const InstanceKlass* klass = this;
2322 while (klass != nullptr) {
2323 if (klass->has_been_redefined()) {
2324 return true;
2325 }
2326 klass = klass->super();
2327 }
2328 return false;
2329 }
2330 #endif
2703 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2704
2705 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2706 / itableOffsetEntry::size();
2707
2708 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2709 if (ioe->interface_klass() != nullptr) {
2710 it->push(ioe->interface_klass_addr());
2711 itableMethodEntry* ime = ioe->first_method_entry(this);
2712 int n = klassItable::method_count_for_interface(ioe->interface_klass());
2713 for (int index = 0; index < n; index ++) {
2714 it->push(ime[index].method_addr());
2715 }
2716 }
2717 }
2718 }
2719
2720 it->push(&_nest_host);
2721 it->push(&_nest_members);
2722 it->push(&_permitted_subclasses);
2723 it->push(&_record_components);
2724
2725 if (CDSConfig::is_dumping_full_module_graph() && !defined_by_other_loaders()) {
2726 it->push(&_package_entry);
2727 }
2728 }
2729
2730 #if INCLUDE_CDS
2731 void InstanceKlass::remove_unshareable_info() {
2732
2733 if (is_linked()) {
2734 assert(can_be_verified_at_dumptime(), "must be");
2735 // Remember this so we can avoid walking the hierarchy at runtime.
2736 set_verified_at_dump_time();
2737 }
2738
2739 _misc_flags.set_has_init_deps_processed(false);
2740
2741 Klass::remove_unshareable_info();
2742
2743 if (SystemDictionaryShared::has_class_failed_verification(this)) {
2755
2756 { // Otherwise this needs to take out the Compile_lock.
2757 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2758 init_implementor();
2759 }
2760
2761 // Call remove_unshareable_info() on other objects that belong to this class, except
2762 // for constants()->remove_unshareable_info(), which is called in a separate pass in
2763 // ArchiveBuilder::make_klasses_shareable(),
2764
2765 for (int i = 0; i < methods()->length(); i++) {
2766 Method* m = methods()->at(i);
2767 m->remove_unshareable_info();
2768 }
2769
2770 // do array classes also.
2771 if (array_klasses() != nullptr) {
2772 array_klasses()->remove_unshareable_info();
2773 }
2774
2775 // These are not allocated from metaspace. They are safe to set to null.
2776 _source_debug_extension = nullptr;
2777 _dep_context = nullptr;
2778 _osr_nmethods_head = nullptr;
2779 #if INCLUDE_JVMTI
2780 _breakpoints = nullptr;
2781 _previous_versions = nullptr;
2782 _cached_class_file = nullptr;
2783 _jvmti_cached_class_field_map = nullptr;
2784 #endif
2785
2786 _init_thread = nullptr;
2787 _methods_jmethod_ids = nullptr;
2788 _jni_ids = nullptr;
2789 _oop_map_cache = nullptr;
2790 if (CDSConfig::is_dumping_method_handles() && HeapShared::is_lambda_proxy_klass(this)) {
2791 // keep _nest_host
2792 } else {
2793 // clear _nest_host to ensure re-load at runtime
2794 _nest_host = nullptr;
2795 }
2831 void InstanceKlass::compute_has_loops_flag_for_methods() {
2832 Array<Method*>* methods = this->methods();
2833 for (int index = 0; index < methods->length(); ++index) {
2834 Method* m = methods->at(index);
2835 if (!m->is_overpass()) { // work around JDK-8305771
2836 m->compute_has_loops_flag();
2837 }
2838 }
2839 }
2840
2841 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
2842 PackageEntry* pkg_entry, TRAPS) {
2843 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
2844 // before the InstanceKlass is added to the SystemDictionary. Make
2845 // sure the current state is <loaded.
2846 assert(!is_loaded(), "invalid init state");
2847 assert(!shared_loading_failed(), "Must not try to load failed class again");
2848 set_package(loader_data, pkg_entry, CHECK);
2849 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2850
2851 Array<Method*>* methods = this->methods();
2852 int num_methods = methods->length();
2853 for (int index = 0; index < num_methods; ++index) {
2854 methods->at(index)->restore_unshareable_info(CHECK);
2855 }
2856 #if INCLUDE_JVMTI
2857 if (JvmtiExport::has_redefined_a_class()) {
2858 // Reinitialize vtable because RedefineClasses may have changed some
2859 // entries in this vtable for super classes so the CDS vtable might
2860 // point to old or obsolete entries. RedefineClasses doesn't fix up
2861 // vtables in the shared system dictionary, only the main one.
2862 // It also redefines the itable too so fix that too.
2863 // First fix any default methods that point to a super class that may
2864 // have been redefined.
2865 bool trace_name_printed = false;
2866 adjust_default_methods(&trace_name_printed);
2867 if (verified_at_dump_time()) {
2868 // Initialize vtable and itable for classes which can be verified at dump time.
2869 // Unlinked classes such as old classes with major version < 50 cannot be verified
2870 // at dump time.
2871 vtable().initialize_vtable();
2872 itable().initialize_itable();
2873 }
2874 }
2875 #endif // INCLUDE_JVMTI
2876
2877 // restore constant pool resolved references
2878 constants()->restore_unshareable_info(CHECK);
2879
2880 if (array_klasses() != nullptr) {
2881 // To get a consistent list of classes we need MultiArray_lock to ensure
2882 // array classes aren't observed while they are being restored.
2883 RecursiveLocker rl(MultiArray_lock, THREAD);
2884 assert(this == array_klasses()->bottom_klass(), "sanity");
2885 // Array classes have null protection domain.
2886 // --> see ArrayKlass::complete_create_array_klass()
2887 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
2888 }
2889
2890 // Initialize @ValueBased class annotation if not already set in the archived klass.
2891 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
2892 set_is_value_based();
2893 }
2894
2895 DEBUG_ONLY(FieldInfoStream::validate_search_table(_constants, _fieldinfo_stream, _fieldinfo_search_table));
2896 }
2897
2898 bool InstanceKlass::can_be_verified_at_dumptime() const {
2899 if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(this)) {
2900 // This is a class that was dumped into the base archive, so we know
2901 // it was verified at dump time.
2902 return true;
2903 }
2904
2905 if (CDSConfig::is_preserving_verification_constraints()) {
2906 return true;
3022 constants()->release_C_heap_structures();
3023 }
3024 }
3025
3026 // The constant pool is on stack if any of the methods are executing or
3027 // referenced by handles.
3028 bool InstanceKlass::on_stack() const {
3029 return _constants->on_stack();
3030 }
3031
3032 Symbol* InstanceKlass::source_file_name() const { return _constants->source_file_name(); }
3033 u2 InstanceKlass::source_file_name_index() const { return _constants->source_file_name_index(); }
3034 void InstanceKlass::set_source_file_name_index(u2 sourcefile_index) { _constants->set_source_file_name_index(sourcefile_index); }
3035
3036 // minor and major version numbers of class file
3037 u2 InstanceKlass::minor_version() const { return _constants->minor_version(); }
3038 void InstanceKlass::set_minor_version(u2 minor_version) { _constants->set_minor_version(minor_version); }
3039 u2 InstanceKlass::major_version() const { return _constants->major_version(); }
3040 void InstanceKlass::set_major_version(u2 major_version) { _constants->set_major_version(major_version); }
3041
3042 const InstanceKlass* InstanceKlass::get_klass_version(int version) const {
3043 for (const InstanceKlass* ik = this; ik != nullptr; ik = ik->previous_versions()) {
3044 if (ik->constants()->version() == version) {
3045 return ik;
3046 }
3047 }
3048 return nullptr;
3049 }
3050
3051 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
3052 if (array == nullptr) {
3053 _source_debug_extension = nullptr;
3054 } else {
3055 // Adding one to the attribute length in order to store a null terminator
3056 // character could cause an overflow because the attribute length is
3057 // already coded with an u4 in the classfile, but in practice, it's
3058 // unlikely to happen.
3059 assert((length+1) > length, "Overflow checking");
3060 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
3061 for (int i = 0; i < length; i++) {
3062 sde[i] = array[i];
3063 }
3064 sde[length] = '\0';
3065 _source_debug_extension = sde;
3066 }
3067 }
3068
3069 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); }
3070 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); }
3071 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); }
3072
3073 const char* InstanceKlass::signature_name() const {
3074
3075 // Get the internal name as a c string
3076 const char* src = (const char*) (name()->as_C_string());
3077 const int src_length = (int)strlen(src);
3078
3079 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
3080
3081 // Add L as type indicator
3082 int dest_index = 0;
3083 dest[dest_index++] = JVM_SIGNATURE_CLASS;
3084
3085 // Add the actual class name
3086 for (int src_index = 0; src_index < src_length; ) {
3087 dest[dest_index++] = src[src_index++];
3088 }
3089
3090 if (is_hidden()) { // Replace the last '+' with a '.'.
3091 for (int index = (int)src_length; index > 0; index--) {
3092 if (dest[index] == '+') {
3093 dest[index] = JVM_SIGNATURE_DOT;
3094 break;
3095 }
3096 }
3097 }
3098
3099 // Add the semicolon and the null
3100 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3101 dest[dest_index] = '\0';
3102 return dest;
3103 }
3344 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3345 constantPoolHandle i_cp(THREAD, constants());
3346 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3347 int ioff = iter.inner_class_info_index();
3348 if (ioff != 0) {
3349 // Check to see if the name matches the class we're looking for
3350 // before attempting to find the class.
3351 if (i_cp->klass_name_at_matches(this, ioff)) {
3352 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3353 if (this == inner_klass) {
3354 *ooff = iter.outer_class_info_index();
3355 *noff = iter.inner_name_index();
3356 return true;
3357 }
3358 }
3359 }
3360 }
3361 return false;
3362 }
3363
3364 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3365 InstanceKlass* outer_klass = nullptr;
3366 *inner_is_member = false;
3367 int ooff = 0, noff = 0;
3368 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3369 if (has_inner_classes_attr) {
3370 constantPoolHandle i_cp(THREAD, constants());
3371 if (ooff != 0) {
3372 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3373 if (!ok->is_instance_klass()) {
3374 // If the outer class is not an instance klass then it cannot have
3375 // declared any inner classes.
3376 ResourceMark rm(THREAD);
3377 // Names are all known to be < 64k so we know this formatted message is not excessively large.
3378 Exceptions::fthrow(
3379 THREAD_AND_LOCATION,
3380 vmSymbols::java_lang_IncompatibleClassChangeError(),
3381 "%s and %s disagree on InnerClasses attribute",
3382 ok->external_name(),
3383 external_name());
3410 u2 InstanceKlass::compute_modifier_flags() const {
3411 u2 access = access_flags().as_unsigned_short();
3412
3413 // But check if it happens to be member class.
3414 InnerClassesIterator iter(this);
3415 for (; !iter.done(); iter.next()) {
3416 int ioff = iter.inner_class_info_index();
3417 // Inner class attribute can be zero, skip it.
3418 // Strange but true: JVM spec. allows null inner class refs.
3419 if (ioff == 0) continue;
3420
3421 // only look at classes that are already loaded
3422 // since we are looking for the flags for our self.
3423 Symbol* inner_name = constants()->klass_name_at(ioff);
3424 if (name() == inner_name) {
3425 // This is really a member class.
3426 access = iter.inner_access_flags();
3427 break;
3428 }
3429 }
3430 // Remember to strip ACC_SUPER bit
3431 return (access & (~JVM_ACC_SUPER));
3432 }
3433
3434 jint InstanceKlass::jvmti_class_status() const {
3435 jint result = 0;
3436
3437 if (is_linked()) {
3438 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3439 }
3440
3441 if (is_initialized()) {
3442 assert(is_linked(), "Class status is not consistent");
3443 result |= JVMTI_CLASS_STATUS_INITIALIZED;
3444 }
3445 if (is_in_error_state()) {
3446 result |= JVMTI_CLASS_STATUS_ERROR;
3447 }
3448 return result;
3449 }
3450
3451 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
3665 }
3666 osr = osr->osr_link();
3667 }
3668
3669 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
3670 if (best != nullptr && best->comp_level() >= comp_level) {
3671 return best;
3672 }
3673 return nullptr;
3674 }
3675
3676 // -----------------------------------------------------------------------------------------------------
3677 // Printing
3678
3679 #define BULLET " - "
3680
3681 static const char* state_names[] = {
3682 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3683 };
3684
3685 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3686 for (int i = 0; i < len; i++) {
3687 intptr_t e = start[i];
3688 st->print("%d : " INTPTR_FORMAT, i, e);
3689 if (MetaspaceObj::is_valid((Metadata*)e)) {
3690 st->print(" ");
3691 ((Metadata*)e)->print_value_on(st);
3692 }
3693 st->cr();
3694 }
3695 }
3696
3697 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3698 return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3699 }
3700
3701 const char* InstanceKlass::init_state_name() const {
3702 return state_names[init_state()];
3703 }
3704
3705 void InstanceKlass::print_on(outputStream* st) const {
3706 assert(is_klass(), "must be klass");
3707 Klass::print_on(st);
3708
3709 st->print(BULLET"instance size: %d", size_helper()); st->cr();
3710 st->print(BULLET"klass size: %d", size()); st->cr();
3711 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
3712 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
3713 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
3714 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
3715 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3716 st->print(BULLET"sub: ");
3717 Klass* sub = subklass();
3718 int n;
3719 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3720 if (n < MaxSubklassPrintSize) {
3721 sub->print_value_on(st);
3722 st->print(" ");
3723 }
3724 }
3725 if (n >= MaxSubklassPrintSize) st->print("(%zd more klasses...)", n - MaxSubklassPrintSize);
3726 st->cr();
3727
3728 if (is_interface()) {
3729 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
3730 if (nof_implementors() == 1) {
3731 st->print_cr(BULLET"implementor: ");
3732 st->print(" ");
3733 implementor()->print_value_on(st);
3734 st->cr();
3735 }
3736 }
3737
3738 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3739 st->print(BULLET"methods: "); methods()->print_value_on(st); st->cr();
3740 if (Verbose || WizardMode) {
3741 Array<Method*>* method_array = methods();
3742 for (int i = 0; i < method_array->length(); i++) {
3743 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3744 }
3745 }
3746 st->print(BULLET"method ordering: "); method_ordering()->print_value_on(st); st->cr();
3747 if (default_methods() != nullptr) {
3748 st->print(BULLET"default_methods: "); default_methods()->print_value_on(st); st->cr();
3749 if (Verbose) {
3750 Array<Method*>* method_array = default_methods();
3751 for (int i = 0; i < method_array->length(); i++) {
3752 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3753 }
3754 }
3755 }
3756 print_on_maybe_null(st, BULLET"default vtable indices: ", default_vtable_indices());
3757 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
3758 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3759
3760 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr();
3761
3762 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr();
3763 st->print(BULLET"secondary bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap); st->cr();
3764
3765 if (secondary_supers() != nullptr) {
3766 if (Verbose) {
3767 bool is_hashed = (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL);
3768 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length());
3769 for (int i = 0; i < _secondary_supers->length(); i++) {
3770 ResourceMark rm; // for external_name()
3771 Klass* secondary_super = _secondary_supers->at(i);
3772 st->print(BULLET"%2d:", i);
3773 if (is_hashed) {
3774 int home_slot = compute_home_slot(secondary_super, _secondary_supers_bitmap);
3775 int distance = (i - home_slot) & SECONDARY_SUPERS_TABLE_MASK;
3776 st->print(" dist:%02d:", distance);
3777 }
3778 st->print_cr(" %p %s", secondary_super, secondary_super->external_name());
3779 }
3780 }
3781 }
3782 st->print(BULLET"constants: "); constants()->print_value_on(st); st->cr();
3783
3784 print_on_maybe_null(st, BULLET"class loader data: ", class_loader_data());
3785 print_on_maybe_null(st, BULLET"source file: ", source_file_name());
3786 if (source_debug_extension() != nullptr) {
3787 st->print(BULLET"source debug extension: ");
3788 st->print("%s", source_debug_extension());
3789 st->cr();
3790 }
3791 print_on_maybe_null(st, BULLET"class annotations: ", class_annotations());
3792 print_on_maybe_null(st, BULLET"class type annotations: ", class_type_annotations());
3793 print_on_maybe_null(st, BULLET"field annotations: ", fields_annotations());
3794 print_on_maybe_null(st, BULLET"field type annotations: ", fields_type_annotations());
3795 {
3796 bool have_pv = false;
3797 // previous versions are linked together through the InstanceKlass
3798 for (InstanceKlass* pv_node = previous_versions();
3799 pv_node != nullptr;
3800 pv_node = pv_node->previous_versions()) {
3801 if (!have_pv)
3802 st->print(BULLET"previous version: ");
3803 have_pv = true;
3804 pv_node->constants()->print_value_on(st);
3805 }
3806 if (have_pv) st->cr();
3807 }
3808
3809 print_on_maybe_null(st, BULLET"generic signature: ", generic_signature());
3810 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
3811 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();
3812 print_on_maybe_null(st, BULLET"record components: ", record_components());
3813 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();
3814 if (java_mirror() != nullptr) {
3815 st->print(BULLET"java mirror: ");
3816 java_mirror()->print_value_on(st);
3817 st->cr();
3818 } else {
3819 st->print_cr(BULLET"java mirror: null");
3820 }
3821 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3822 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);
3823 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3824 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_itable(), itable_length(), st);
3825 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3826
3827 FieldPrinter print_static_field(st);
3828 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3829 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3830 FieldPrinter print_nonstatic_field(st);
3831 InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3832 ik->print_nonstatic_fields(&print_nonstatic_field);
3833
3834 st->print(BULLET"non-static oop maps (%d entries): ", nonstatic_oop_map_count());
3835 OopMapBlock* map = start_of_nonstatic_oop_maps();
3836 OopMapBlock* end_map = map + nonstatic_oop_map_count();
3837 while (map < end_map) {
3838 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3839 map++;
3840 }
3841 st->cr();
3842
3843 if (fieldinfo_search_table() != nullptr) {
3844 st->print_cr(BULLET"---- field info search table:");
3845 FieldInfoStream::print_search_table(st, _constants, _fieldinfo_stream, _fieldinfo_search_table);
3846 }
3847 }
3848
3849 void InstanceKlass::print_value_on(outputStream* st) const {
3850 assert(is_klass(), "must be klass");
3851 if (Verbose || WizardMode) access_flags().print_on(st);
3852 name()->print_value_on(st);
3853 }
3854
3855 void FieldPrinter::do_field(fieldDescriptor* fd) {
3856 _st->print(BULLET);
3857 if (_obj == nullptr) {
3858 fd->print_on(_st);
3859 _st->cr();
3860 } else {
3861 fd->print_on_for(_st, _obj);
3862 _st->cr();
3863 }
3864 }
3865
3866
3867 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3868 Klass::oop_print_on(obj, st);
3869
3870 if (this == vmClasses::String_klass()) {
3871 typeArrayOop value = java_lang_String::value(obj);
3872 juint length = java_lang_String::length(obj);
3873 if (value != nullptr &&
3874 value->is_typeArray() &&
3875 length <= (juint) value->length()) {
3876 st->print(BULLET"string: ");
3877 java_lang_String::print(obj, st);
3878 st->cr();
3879 }
3880 }
3881
3882 st->print_cr(BULLET"---- fields (total size %zu words):", oop_size(obj));
3883 FieldPrinter print_field(st, obj);
3884 print_nonstatic_fields(&print_field);
3885
3886 if (this == vmClasses::Class_klass()) {
3887 st->print(BULLET"signature: ");
3888 java_lang_Class::print_signature(obj, st);
3889 st->cr();
3890 Klass* real_klass = java_lang_Class::as_Klass(obj);
3891 if (real_klass != nullptr && real_klass->is_instance_klass()) {
3892 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj));
3893 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3894 }
3895 } else if (this == vmClasses::MethodType_klass()) {
3896 st->print(BULLET"signature: ");
3897 java_lang_invoke_MethodType::print_signature(obj, st);
3898 st->cr();
3899 }
3900 }
3901
3902 #ifndef PRODUCT
3903
|
47 #include "compiler/compileBroker.hpp"
48 #include "gc/shared/collectedHeap.inline.hpp"
49 #include "interpreter/bytecodeStream.hpp"
50 #include "interpreter/oopMapCache.hpp"
51 #include "interpreter/rewriter.hpp"
52 #include "jvm.h"
53 #include "jvmtifiles/jvmti.h"
54 #include "klass.inline.hpp"
55 #include "logging/log.hpp"
56 #include "logging/logMessage.hpp"
57 #include "logging/logStream.hpp"
58 #include "memory/allocation.inline.hpp"
59 #include "memory/iterator.inline.hpp"
60 #include "memory/metadataFactory.hpp"
61 #include "memory/metaspaceClosure.hpp"
62 #include "memory/oopFactory.hpp"
63 #include "memory/resourceArea.hpp"
64 #include "memory/universe.hpp"
65 #include "oops/constantPool.hpp"
66 #include "oops/fieldStreams.inline.hpp"
67 #include "oops/inlineKlass.hpp"
68 #include "oops/instanceClassLoaderKlass.hpp"
69 #include "oops/instanceKlass.inline.hpp"
70 #include "oops/instanceMirrorKlass.hpp"
71 #include "oops/instanceOop.hpp"
72 #include "oops/instanceStackChunkKlass.hpp"
73 #include "oops/klass.inline.hpp"
74 #include "oops/layoutKind.hpp"
75 #include "oops/markWord.hpp"
76 #include "oops/method.hpp"
77 #include "oops/oop.inline.hpp"
78 #include "oops/recordComponent.hpp"
79 #include "oops/refArrayKlass.hpp"
80 #include "oops/symbol.hpp"
81 #include "prims/jvmtiExport.hpp"
82 #include "prims/jvmtiRedefineClasses.hpp"
83 #include "prims/jvmtiThreadState.hpp"
84 #include "prims/methodComparator.hpp"
85 #include "runtime/arguments.hpp"
86 #include "runtime/atomicAccess.hpp"
87 #include "runtime/deoptimization.hpp"
88 #include "runtime/fieldDescriptor.inline.hpp"
89 #include "runtime/handles.inline.hpp"
90 #include "runtime/javaCalls.hpp"
91 #include "runtime/javaThread.inline.hpp"
92 #include "runtime/mutexLocker.hpp"
93 #include "runtime/orderAccess.hpp"
94 #include "runtime/os.inline.hpp"
95 #include "runtime/reflection.hpp"
96 #include "runtime/synchronizer.hpp"
97 #include "runtime/threads.hpp"
98 #include "services/classLoadingService.hpp"
99 #include "services/finalizerService.hpp"
100 #include "services/threadService.hpp"
101 #include "utilities/dtrace.hpp"
102 #include "utilities/events.hpp"
103 #include "utilities/macros.hpp"
104 #include "utilities/nativeStackPrinter.hpp"
105 #include "utilities/ostream.hpp"
106 #include "utilities/stringUtils.hpp"
107 #ifdef COMPILER1
108 #include "c1/c1_Compiler.hpp"
109 #endif
110 #if INCLUDE_JFR
111 #include "jfr/jfrEvents.hpp"
112 #endif
113
114 #ifdef DTRACE_ENABLED
115
116
117 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
118 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
119 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
120 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
121 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
122 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
123 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
124 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
125 #define DTRACE_CLASSINIT_PROBE(type, thread_type) \
138 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait) \
139 { \
140 char* data = nullptr; \
141 int len = 0; \
142 Symbol* clss_name = name(); \
143 if (clss_name != nullptr) { \
144 data = (char*)clss_name->bytes(); \
145 len = clss_name->utf8_length(); \
146 } \
147 HOTSPOT_CLASS_INITIALIZATION_##type( \
148 data, len, (void*)class_loader(), thread_type, wait); \
149 }
150
151 #else // ndef DTRACE_ENABLED
152
153 #define DTRACE_CLASSINIT_PROBE(type, thread_type)
154 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)
155
156 #endif // ndef DTRACE_ENABLED
157
158 void InlineLayoutInfo::metaspace_pointers_do(MetaspaceClosure* it) {
159 log_trace(cds)("Iter(InlineFieldInfo): %p", this);
160 it->push(&_klass);
161 }
162
163 void InlineLayoutInfo::print() const {
164 print_on(tty);
165 }
166
167 void InlineLayoutInfo::print_on(outputStream* st) const {
168 st->print_cr("_klass: " PTR_FORMAT, p2i(_klass));
169 if (_klass != nullptr) {
170 StreamIndentor si(st);
171 _klass->print_on(st);
172 st->cr();
173 }
174
175 st->print("_layout: ");
176 LayoutKindHelper::print_on(_kind, st);
177 st->cr();
178
179 st->print("_null_marker_offset: %d", _null_marker_offset);
180 }
181
182 // A value class is considered naturally atomic if its layout,
183 // once all fields flattening have been applied, contains a single primitive
184 // or oop field. Because primitive types and oops are already handled
185 // atomically by the JVM, it means that there's no need to take
186 // special precautions when reading or writing this value to guarantee
187 // cross-fields invariants. Nullability has to be taken into consideration,
188 // as the null-marker has to be considered as a pseudo-field which must
189 // be kept consistent with the payload. The only kind of value class
190 // that can be considered naturally atomic when nullable is the empty
191 // value classes because the dummy field is re-used as a null-marker.
192 bool InstanceKlass::is_naturally_atomic(bool null_free) const {
193 assert(!is_identity_class(), "Doesn't have sense for an identity class");
194 if (null_free) {
195 // No extra null-marker, just check the layout of the fields
196 return _misc_flags.is_naturally_atomic();
197 } else {
198 // Requires a null-marker, can't have any other fields
199 return InlineKlass::cast(this)->is_empty_inline_type();
200 }
201 }
202
203 bool InstanceKlass::_finalization_enabled = true;
204 static int call_class_initializer_counter = 0; // for debugging
205
206 static inline bool is_class_loader(const Symbol* class_name,
207 const ClassFileParser& parser) {
208 assert(class_name != nullptr, "invariant");
209
210 if (class_name == vmSymbols::java_lang_ClassLoader()) {
211 return true;
212 }
213
214 if (vmClasses::ClassLoader_klass_is_loaded()) {
215 const Klass* const super_klass = parser.super_klass();
216 if (super_klass != nullptr) {
217 if (super_klass->is_subtype_of(vmClasses::ClassLoader_klass())) {
218 return true;
219 }
220 }
221 }
222 return false;
223 }
224
225 bool InstanceKlass::field_is_null_free_inline_type(int index) const {
226 return field(index).field_flags().is_null_free_inline_type();
227 }
228
229 bool InstanceKlass::is_class_in_loadable_descriptors_attribute(Symbol* name) const {
230 if (_loadable_descriptors == nullptr) return false;
231 for (int i = 0; i < _loadable_descriptors->length(); i++) {
232 Symbol* class_name = _constants->symbol_at(_loadable_descriptors->at(i));
233 if (class_name == name) return true;
234 }
235 return false;
236 }
237
238 static inline bool is_stack_chunk_class(const Symbol* class_name,
239 const ClassLoaderData* loader_data) {
240 return (class_name == vmSymbols::jdk_internal_vm_StackChunk() &&
241 loader_data->is_the_null_class_loader_data());
242 }
243
244 // private: called to verify that k is a static member of this nest.
245 // We know that k is an instance class in the same package and hence the
246 // same classloader.
247 bool InstanceKlass::has_nest_member(JavaThread* current, InstanceKlass* k) const {
248 assert(!is_hidden(), "unexpected hidden class");
249 if (_nest_members == nullptr || _nest_members == Universe::the_empty_short_array()) {
250 if (log_is_enabled(Trace, class, nestmates)) {
251 ResourceMark rm(current);
252 log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
253 k->external_name(), this->external_name());
254 }
255 return false;
256 }
257
505 log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
506 this->external_name(),
507 access ? "" : "NOT ",
508 k->external_name());
509 return access;
510 }
511
512 const char* InstanceKlass::nest_host_error() {
513 if (_nest_host_index == 0) {
514 return nullptr;
515 } else {
516 constantPoolHandle cph(Thread::current(), constants());
517 return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index);
518 }
519 }
520
521 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
522 const int size = InstanceKlass::size(parser.vtable_size(),
523 parser.itable_size(),
524 nonstatic_oop_map_size(parser.total_oop_map_count()),
525 parser.is_interface(),
526 parser.is_inline_type());
527
528 const Symbol* const class_name = parser.class_name();
529 assert(class_name != nullptr, "invariant");
530 ClassLoaderData* loader_data = parser.loader_data();
531 assert(loader_data != nullptr, "invariant");
532
533 InstanceKlass* ik;
534
535 // Allocation
536 if (parser.is_instance_ref_klass()) {
537 // java.lang.ref.Reference
538 ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
539 } else if (class_name == vmSymbols::java_lang_Class()) {
540 // mirror - java.lang.Class
541 ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
542 } else if (is_stack_chunk_class(class_name, loader_data)) {
543 // stack chunk
544 ik = new (loader_data, size, THREAD) InstanceStackChunkKlass(parser);
545 } else if (is_class_loader(class_name, parser)) {
546 // class loader - java.lang.ClassLoader
547 ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);
548 } else if (parser.is_inline_type()) {
549 // inline type
550 ik = new (loader_data, size, THREAD) InlineKlass(parser);
551 } else {
552 // normal
553 ik = new (loader_data, size, THREAD) InstanceKlass(parser);
554 }
555
556 assert(ik == nullptr || CompressedKlassPointers::is_encodable(ik),
557 "Klass " PTR_FORMAT "needs a narrow Klass ID, but is not encodable", p2i(ik));
558
559 // Check for pending exception before adding to the loader data and incrementing
560 // class count. Can get OOM here.
561 if (HAS_PENDING_EXCEPTION) {
562 return nullptr;
563 }
564
565 #ifdef ASSERT
566 ik->bounds_check((address) ik->start_of_vtable(), false, size);
567 ik->bounds_check((address) ik->start_of_itable(), false, size);
568 ik->bounds_check((address) ik->end_of_itable(), true, size);
569 ik->bounds_check((address) ik->end_of_nonstatic_oop_maps(), true, size);
570 #endif //ASSERT
571 return ik;
572 }
573
574 #ifndef PRODUCT
575 bool InstanceKlass::bounds_check(address addr, bool edge_ok, intptr_t size_in_bytes) const {
576 const char* bad = nullptr;
577 address end = nullptr;
578 if (addr < (address)this) {
579 bad = "before";
580 } else if (addr == (address)this) {
581 if (edge_ok) return true;
582 bad = "just before";
583 } else if (addr == (end = (address)this + sizeof(intptr_t) * (size_in_bytes < 0 ? size() : size_in_bytes))) {
584 if (edge_ok) return true;
585 bad = "just after";
586 } else if (addr > end) {
587 bad = "after";
588 } else {
589 return true;
590 }
591 tty->print_cr("%s object bounds: " INTPTR_FORMAT " [" INTPTR_FORMAT ".." INTPTR_FORMAT "]",
592 bad, (intptr_t)addr, (intptr_t)this, (intptr_t)end);
593 Verbose = WizardMode = true; this->print(); //@@
594 return false;
595 }
596 #endif //PRODUCT
597
598 // copy method ordering from resource area to Metaspace
599 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
600 if (m != nullptr) {
601 // allocate a new array and copy contents (memcpy?)
602 _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
603 for (int i = 0; i < m->length(); i++) {
604 _method_ordering->at_put(i, m->at(i));
605 }
606 } else {
607 _method_ordering = Universe::the_empty_int_array();
608 }
609 }
610
611 // create a new array of vtable_indices for default methods
612 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
613 Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
614 assert(default_vtable_indices() == nullptr, "only create once");
615 set_default_vtable_indices(vtable_indices);
616 return vtable_indices;
617 }
618
619
620 InstanceKlass::InstanceKlass() {
621 assert(CDSConfig::is_dumping_static_archive() || CDSConfig::is_using_archive(), "only for CDS");
622 }
623
624 InstanceKlass::InstanceKlass(const ClassFileParser& parser, KlassKind kind, markWord prototype_header, ReferenceType reference_type) :
625 Klass(kind, prototype_header),
626 _nest_members(nullptr),
627 _nest_host(nullptr),
628 _permitted_subclasses(nullptr),
629 _record_components(nullptr),
630 _static_field_size(parser.static_field_size()),
631 _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
632 _itable_len(parser.itable_size()),
633 _nest_host_index(0),
634 _init_state(allocated),
635 _reference_type(reference_type),
636 _acmp_maps_offset(0),
637 _init_thread(nullptr),
638 _inline_layout_info_array(nullptr),
639 _loadable_descriptors(nullptr),
640 _acmp_maps_array(nullptr),
641 _adr_inline_klass_members(nullptr)
642 {
643 set_vtable_length(parser.vtable_size());
644 set_access_flags(parser.access_flags());
645 if (parser.is_hidden()) set_is_hidden();
646 set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
647 false));
648 if (parser.has_inlined_fields()) {
649 set_has_inlined_fields();
650 }
651
652 assert(nullptr == _methods, "underlying memory not zeroed?");
653 assert(is_instance_klass(), "is layout incorrect?");
654 assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
655 }
656
657 void InstanceKlass::set_is_cloneable() {
658 if (name() == vmSymbols::java_lang_invoke_MemberName()) {
659 assert(is_final(), "no subclasses allowed");
660 // MemberName cloning should not be intrinsified and always happen in JVM_Clone.
661 } else if (reference_type() != REF_NONE) {
662 // Reference cloning should not be intrinsified and always happen in JVM_Clone.
663 } else {
664 set_is_cloneable_fast();
665 }
666 }
667
668 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
669 Array<Method*>* methods) {
670 if (methods != nullptr && methods != Universe::the_empty_method_array() &&
786
787 deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
788 set_transitive_interfaces(nullptr);
789 set_local_interfaces(nullptr);
790
791 if (fieldinfo_stream() != nullptr && !fieldinfo_stream()->in_aot_cache()) {
792 MetadataFactory::free_array<u1>(loader_data, fieldinfo_stream());
793 }
794 set_fieldinfo_stream(nullptr);
795
796 if (fieldinfo_search_table() != nullptr && !fieldinfo_search_table()->in_aot_cache()) {
797 MetadataFactory::free_array<u1>(loader_data, fieldinfo_search_table());
798 }
799 set_fieldinfo_search_table(nullptr);
800
801 if (fields_status() != nullptr && !fields_status()->in_aot_cache()) {
802 MetadataFactory::free_array<FieldStatus>(loader_data, fields_status());
803 }
804 set_fields_status(nullptr);
805
806 if (inline_layout_info_array() != nullptr) {
807 MetadataFactory::free_array<InlineLayoutInfo>(loader_data, inline_layout_info_array());
808 }
809 set_inline_layout_info_array(nullptr);
810
811 // If a method from a redefined class is using this constant pool, don't
812 // delete it, yet. The new class's previous version will point to this.
813 if (constants() != nullptr) {
814 assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
815 if (!constants()->in_aot_cache()) {
816 HeapShared::remove_scratch_resolved_references(constants());
817 MetadataFactory::free_metadata(loader_data, constants());
818 }
819 // Delete any cached resolution errors for the constant pool
820 SystemDictionary::delete_resolution_error(constants());
821
822 set_constants(nullptr);
823 }
824
825 if (inner_classes() != nullptr &&
826 inner_classes() != Universe::the_empty_short_array() &&
827 !inner_classes()->in_aot_cache()) {
828 MetadataFactory::free_array<jushort>(loader_data, inner_classes());
829 }
830 set_inner_classes(nullptr);
831
832 if (nest_members() != nullptr &&
833 nest_members() != Universe::the_empty_short_array() &&
834 !nest_members()->in_aot_cache()) {
835 MetadataFactory::free_array<jushort>(loader_data, nest_members());
836 }
837 set_nest_members(nullptr);
838
839 if (permitted_subclasses() != nullptr &&
840 permitted_subclasses() != Universe::the_empty_short_array() &&
841 !permitted_subclasses()->in_aot_cache()) {
842 MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
843 }
844 set_permitted_subclasses(nullptr);
845
846 if (loadable_descriptors() != nullptr &&
847 loadable_descriptors() != Universe::the_empty_short_array() &&
848 !loadable_descriptors()->in_aot_cache()) {
849 MetadataFactory::free_array<jushort>(loader_data, loadable_descriptors());
850 }
851 set_loadable_descriptors(nullptr);
852
853 if (acmp_maps_array() != nullptr) {
854 MetadataFactory::free_array<int>(loader_data, acmp_maps_array());
855 }
856 set_acmp_maps_array(nullptr);
857
858 // We should deallocate the Annotations instance if it's not in shared spaces.
859 if (annotations() != nullptr && !annotations()->in_aot_cache()) {
860 MetadataFactory::free_metadata(loader_data, annotations());
861 }
862 set_annotations(nullptr);
863
864 SystemDictionaryShared::handle_class_unloading(this);
865
866 #if INCLUDE_CDS_JAVA_HEAP
867 if (CDSConfig::is_dumping_heap()) {
868 HeapShared::remove_scratch_objects(this);
869 }
870 #endif
871 }
872
873 bool InstanceKlass::is_record() const {
874 return _record_components != nullptr &&
875 is_final() &&
876 super() == vmClasses::Record_klass();
877 }
880 return _permitted_subclasses != nullptr &&
881 _permitted_subclasses != Universe::the_empty_short_array();
882 }
883
884 // JLS 8.9: An enum class is either implicitly final and derives
885 // from java.lang.Enum, or else is implicitly sealed to its
886 // anonymous subclasses. This query detects both kinds.
887 // It does not validate the finality or
888 // sealing conditions: it merely checks for a super of Enum.
889 // This is sufficient for recognizing well-formed enums.
890 bool InstanceKlass::is_enum_subclass() const {
891 InstanceKlass* s = super();
892 return (s == vmClasses::Enum_klass() ||
893 (s != nullptr && s->super() == vmClasses::Enum_klass()));
894 }
895
896 bool InstanceKlass::should_be_initialized() const {
897 return !is_initialized();
898 }
899
900 // Static size helper
901 int InstanceKlass::size(int vtable_length,
902 int itable_length,
903 int nonstatic_oop_map_size,
904 bool is_interface,
905 bool is_inline_type) {
906 return align_metadata_size(header_size() +
907 vtable_length +
908 itable_length +
909 nonstatic_oop_map_size +
910 (is_interface ? (int)sizeof(Klass*) / wordSize : 0) +
911 (is_inline_type ? (int)sizeof(InlineKlass::Members) / wordSize : 0));
912 }
913
914 int InstanceKlass::size() const {
915 return size(vtable_length(),
916 itable_length(),
917 nonstatic_oop_map_size(),
918 is_interface(),
919 is_inline_klass());
920 }
921
922 klassItable InstanceKlass::itable() const {
923 return klassItable(const_cast<InstanceKlass*>(this));
924 }
925
926 // JVMTI spec thinks there are signers and protection domain in the
927 // instanceKlass. These accessors pretend these fields are there.
928 // The hprof specification also thinks these fields are in InstanceKlass.
929 oop InstanceKlass::protection_domain() const {
930 // return the protection_domain from the mirror
931 return java_lang_Class::protection_domain(java_mirror());
932 }
933
934 objArrayOop InstanceKlass::signers() const {
935 // return the signers from the mirror
936 return java_lang_Class::signers(java_mirror());
937 }
938
939 oop InstanceKlass::init_lock() const {
940 // return the init lock from the mirror
941 oop lock = java_lang_Class::init_lock(java_mirror());
1077 #ifdef ASSERT
1078 {
1079 Handle h_init_lock(THREAD, init_lock());
1080 ObjectLocker ol(h_init_lock, THREAD);
1081 assert(!is_initialized(), "sanity");
1082 assert(!is_being_initialized(), "sanity");
1083 assert(!is_in_error_state(), "sanity");
1084 }
1085 #endif
1086
1087 set_init_thread(THREAD);
1088 set_initialization_state_and_notify(fully_initialized, CHECK);
1089 }
1090 #endif
1091
1092 bool InstanceKlass::verify_code(TRAPS) {
1093 // 1) Verify the bytecodes
1094 return Verifier::verify(this, should_verify_class(), THREAD);
1095 }
1096
1097 static void load_classes_from_loadable_descriptors_attribute(InstanceKlass *ik, TRAPS) {
1098 if (ik->loadable_descriptors() != Universe::the_empty_short_array() && PreloadClasses) {
1099 ResourceMark rm(THREAD);
1100 HandleMark hm(THREAD);
1101 for (int i = 0; i < ik->loadable_descriptors()->length(); i++) {
1102 Symbol* sig = ik->constants()->symbol_at(ik->loadable_descriptors()->at(i));
1103 if (!Signature::has_envelope(sig)) continue;
1104 TempNewSymbol class_name = Signature::strip_envelope(sig);
1105 if (class_name == ik->name()) continue;
1106 log_info(class, preload)("Preloading of class %s during linking of class %s "
1107 "because of the class is listed in the LoadableDescriptors attribute",
1108 sig->as_C_string(), ik->name()->as_C_string());
1109 oop loader = ik->class_loader();
1110 Klass* klass = SystemDictionary::resolve_or_null(class_name,
1111 Handle(THREAD, loader), THREAD);
1112 if (HAS_PENDING_EXCEPTION) {
1113 CLEAR_PENDING_EXCEPTION;
1114 }
1115 if (klass != nullptr) {
1116 log_info(class, preload)("Preloading of class %s during linking of class %s "
1117 "(cause: LoadableDescriptors attribute) succeeded",
1118 class_name->as_C_string(), ik->name()->as_C_string());
1119 if (!klass->is_inline_klass()) {
1120 // Non value class are allowed by the current spec, but it could be an indication
1121 // of an issue so let's log a warning
1122 log_info(class, preload)("Preloading of class %s during linking of class %s "
1123 "(cause: LoadableDescriptors attribute) but loaded class is not a value class",
1124 class_name->as_C_string(), ik->name()->as_C_string());
1125 }
1126 } else {
1127 log_info(class, preload)("Preloading of class %s during linking of class %s "
1128 "(cause: LoadableDescriptors attribute) failed",
1129 class_name->as_C_string(), ik->name()->as_C_string());
1130 }
1131 }
1132 }
1133 }
1134
1135 void InstanceKlass::link_class(TRAPS) {
1136 assert(is_loaded(), "must be loaded");
1137 if (!is_linked()) {
1138 link_class_impl(CHECK);
1139 }
1140 }
1141
1142 // Called to verify that a class can link during initialization, without
1143 // throwing a VerifyError.
1144 bool InstanceKlass::link_class_or_fail(TRAPS) {
1145 assert(is_loaded(), "must be loaded");
1146 if (!is_linked()) {
1147 link_class_impl(CHECK_false);
1148 }
1149 return is_linked();
1150 }
1151
1152 bool InstanceKlass::link_class_impl(TRAPS) {
1153 if (CDSConfig::is_dumping_static_archive() && SystemDictionaryShared::has_class_failed_verification(this)) {
1154 // This is for CDS static dump only -- we use the in_error_state to indicate that
1185 THREAD_AND_LOCATION,
1186 vmSymbols::java_lang_IncompatibleClassChangeError(),
1187 "class %s has interface %s as super class",
1188 external_name(),
1189 super_klass->external_name()
1190 );
1191 return false;
1192 }
1193
1194 super_klass->link_class_impl(CHECK_false);
1195 }
1196
1197 // link all interfaces implemented by this class before linking this class
1198 Array<InstanceKlass*>* interfaces = local_interfaces();
1199 int num_interfaces = interfaces->length();
1200 for (int index = 0; index < num_interfaces; index++) {
1201 InstanceKlass* interk = interfaces->at(index);
1202 interk->link_class_impl(CHECK_false);
1203 }
1204
1205 if (Arguments::is_valhalla_enabled()) {
1206 // Aggressively preloading all classes from the LoadableDescriptors attribute
1207 // so inline classes can be scalarized in the calling conventions computed below
1208 load_classes_from_loadable_descriptors_attribute(this, THREAD);
1209 assert(!HAS_PENDING_EXCEPTION, "Shouldn't have pending exceptions from call above");
1210 }
1211
1212 // in case the class is linked in the process of linking its superclasses
1213 if (is_linked()) {
1214 return true;
1215 }
1216
1217 // trace only the link time for this klass that includes
1218 // the verification time
1219 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
1220 ClassLoader::perf_class_link_selftime(),
1221 ClassLoader::perf_classes_linked(),
1222 jt->get_thread_stat()->perf_recursion_counts_addr(),
1223 jt->get_thread_stat()->perf_timers_addr(),
1224 PerfClassTraceTime::CLASS_LINK);
1225
1226 // verification & rewriting
1227 {
1228 HandleMark hm(THREAD);
1229 Handle h_init_lock(THREAD, init_lock());
1230 ObjectLocker ol(h_init_lock, CHECK_PREEMPTABLE_false);
1231 // Don't allow preemption if we link/initialize classes below,
1521 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1522 ss.as_string(), cause);
1523 }
1524 } else {
1525
1526 // Step 6
1527 set_init_state(being_initialized);
1528 set_init_thread(jt);
1529 if (debug_logging_enabled) {
1530 ResourceMark rm(jt);
1531 log_debug(class, init)("Thread \"%s\" is initializing %s",
1532 jt->name(), external_name());
1533 }
1534 }
1535 }
1536
1537 // Block preemption once we are the initializer thread. Unmounting now
1538 // would complicate the reentrant case (identity is platform thread).
1539 NoPreemptMark npm(THREAD);
1540
1541 // Pre-allocating an all-zero value to be used to reset nullable flat storages
1542 if (is_inline_klass()) {
1543 InlineKlass* vk = InlineKlass::cast(this);
1544 if (vk->supports_nullable_layouts()) {
1545 oop val = vk->allocate_instance(THREAD);
1546 if (HAS_PENDING_EXCEPTION) {
1547 Handle e(THREAD, PENDING_EXCEPTION);
1548 CLEAR_PENDING_EXCEPTION;
1549 {
1550 EXCEPTION_MARK;
1551 add_initialization_error(THREAD, e);
1552 // Locks object, set state, and notify all waiting threads
1553 set_initialization_state_and_notify(initialization_error, THREAD);
1554 CLEAR_PENDING_EXCEPTION;
1555 }
1556 THROW_OOP(e());
1557 }
1558 vk->set_null_reset_value(val);
1559 }
1560 }
1561
1562 // Step 7
1563 // Next, if C is a class rather than an interface, initialize it's super class and super
1564 // interfaces.
1565 if (!is_interface()) {
1566 Klass* super_klass = super();
1567 if (super_klass != nullptr && super_klass->should_be_initialized()) {
1568 super_klass->initialize(THREAD);
1569 }
1570 // If C implements any interface that declares a non-static, concrete method,
1571 // the initialization of C triggers initialization of its super interfaces.
1572 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1573 // having a superinterface that declares, non-static, concrete methods
1574 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1575 initialize_super_interfaces(THREAD);
1576 }
1577
1578 // If any exceptions, complete abruptly, throwing the same exception as above.
1579 if (HAS_PENDING_EXCEPTION) {
1580 Handle e(THREAD, PENDING_EXCEPTION);
1581 CLEAR_PENDING_EXCEPTION;
1595 // Step 8
1596 {
1597 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1598 if (class_initializer() != nullptr) {
1599 // Timer includes any side effects of class initialization (resolution,
1600 // etc), but not recursive entry into call_class_initializer().
1601 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1602 ClassLoader::perf_class_init_selftime(),
1603 ClassLoader::perf_classes_inited(),
1604 jt->get_thread_stat()->perf_recursion_counts_addr(),
1605 jt->get_thread_stat()->perf_timers_addr(),
1606 PerfClassTraceTime::CLASS_CLINIT);
1607 call_class_initializer(THREAD);
1608 } else {
1609 // The elapsed time is so small it's not worth counting.
1610 if (UsePerfData) {
1611 ClassLoader::perf_classes_inited()->inc();
1612 }
1613 call_class_initializer(THREAD);
1614 }
1615
1616 if (has_strict_static_fields() && !HAS_PENDING_EXCEPTION) {
1617 // Step 9 also verifies that strict static fields have been initialized.
1618 // Status bits were set in ClassFileParser::post_process_parsed_stream.
1619 // After <clinit>, bits must all be clear, or else we must throw an error.
1620 // This is an extremely fast check, so we won't bother with a timer.
1621 assert(fields_status() != nullptr, "");
1622 Symbol* bad_strict_static = nullptr;
1623 for (int index = 0; index < fields_status()->length(); index++) {
1624 // Very fast loop over single byte array looking for a set bit.
1625 if (fields_status()->adr_at(index)->is_strict_static_unset()) {
1626 // This strict static field has not been set by the class initializer.
1627 // Note that in the common no-error case, we read no field metadata.
1628 // We only unpack it when we need to report an error.
1629 FieldInfo fi = field(index);
1630 bad_strict_static = fi.name(constants());
1631 if (debug_logging_enabled) {
1632 ResourceMark rm(jt);
1633 const char* msg = format_strict_static_message(bad_strict_static);
1634 log_debug(class, init)("%s", msg);
1635 } else {
1636 // If we are not logging, do not bother to look for a second offense.
1637 break;
1638 }
1639 }
1640 }
1641 if (bad_strict_static != nullptr) {
1642 throw_strict_static_exception(bad_strict_static, "is unset after initialization of", THREAD);
1643 }
1644 }
1645 }
1646
1647 // Step 9
1648 if (!HAS_PENDING_EXCEPTION) {
1649 set_initialization_state_and_notify(fully_initialized, CHECK);
1650 DEBUG_ONLY(vtable().verify(tty, true);)
1651 CompilationPolicy::replay_training_at_init(this, THREAD);
1652 }
1653 else {
1654 // Step 10 and 11
1655 Handle e(THREAD, PENDING_EXCEPTION);
1656 CLEAR_PENDING_EXCEPTION;
1657 // JVMTI has already reported the pending exception
1658 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1659 JvmtiExport::clear_detected_exception(jt);
1660 {
1661 EXCEPTION_MARK;
1662 add_initialization_error(THREAD, e);
1663 set_initialization_state_and_notify(initialization_error, THREAD);
1664 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1678 }
1679 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1680 }
1681
1682
1683 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1684 Handle h_init_lock(THREAD, init_lock());
1685 if (h_init_lock() != nullptr) {
1686 ObjectLocker ol(h_init_lock, THREAD);
1687 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1688 set_init_state(state);
1689 fence_and_clear_init_lock();
1690 ol.notify_all(CHECK);
1691 } else {
1692 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1693 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1694 set_init_state(state);
1695 }
1696 }
1697
1698 void InstanceKlass::notify_strict_static_access(int field_index, bool is_writing, TRAPS) {
1699 guarantee(field_index >= 0 && field_index < fields_status()->length(), "valid field index");
1700 DEBUG_ONLY(FieldInfo debugfi = field(field_index));
1701 assert(debugfi.access_flags().is_strict(), "");
1702 assert(debugfi.access_flags().is_static(), "");
1703 FieldStatus& fs = *fields_status()->adr_at(field_index);
1704 LogTarget(Trace, class, init) lt;
1705 if (lt.is_enabled()) {
1706 ResourceMark rm(THREAD);
1707 LogStream ls(lt);
1708 FieldInfo fi = field(field_index);
1709 ls.print("notify %s %s %s%s ",
1710 external_name(), is_writing? "Write" : "Read",
1711 fs.is_strict_static_unset() ? "Unset" : "(set)",
1712 fs.is_strict_static_unread() ? "+Unread" : "");
1713 fi.print(&ls, constants());
1714 }
1715 if (fs.is_strict_static_unset()) {
1716 assert(fs.is_strict_static_unread(), "ClassFileParser resp.");
1717 // If it is not set, there are only two reasonable things we can do here:
1718 // - mark it set if this is putstatic
1719 // - throw an error (Read-Before-Write) if this is getstatic
1720
1721 // The unset state is (or should be) transient, and observable only in one
1722 // thread during the execution of <clinit>. Something is wrong here as this
1723 // should not be possible
1724 guarantee(is_reentrant_initialization(THREAD), "unscoped access to strict static");
1725 if (is_writing) {
1726 // clear the "unset" bit, since the field is actually going to be written
1727 fs.update_strict_static_unset(false);
1728 } else {
1729 // throw an IllegalStateException, since we are reading before writing
1730 // see also InstanceKlass::initialize_impl, Step 8 (at end)
1731 Symbol* bad_strict_static = field(field_index).name(constants());
1732 throw_strict_static_exception(bad_strict_static, "is unset before first read in", CHECK);
1733 }
1734 } else {
1735 // Ensure no write after read for final strict statics
1736 FieldInfo fi = field(field_index);
1737 bool is_final = fi.access_flags().is_final();
1738 if (is_final) {
1739 // no final write after read, so observing a constant freezes it, as if <clinit> ended early
1740 // (maybe we could trust the constant a little earlier, before <clinit> ends)
1741 if (is_writing && !fs.is_strict_static_unread()) {
1742 Symbol* bad_strict_static = fi.name(constants());
1743 throw_strict_static_exception(bad_strict_static, "is set after read (as final) in", CHECK);
1744 } else if (!is_writing && fs.is_strict_static_unread()) {
1745 fs.update_strict_static_unread(false);
1746 }
1747 }
1748 }
1749 }
1750
1751 void InstanceKlass::throw_strict_static_exception(Symbol* field_name, const char* when, TRAPS) {
1752 ResourceMark rm(THREAD);
1753 const char* msg = format_strict_static_message(field_name, when);
1754 THROW_MSG(vmSymbols::java_lang_IllegalStateException(), msg);
1755 }
1756
1757 const char* InstanceKlass::format_strict_static_message(Symbol* field_name, const char* when) {
1758 stringStream ss;
1759 ss.print("Strict static \"%s\" %s %s",
1760 field_name->as_C_string(),
1761 when == nullptr ? "is unset in" : when,
1762 external_name());
1763 return ss.as_string();
1764 }
1765
1766 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1767 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1768 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1769 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1770
1771 DeoptimizationScope deopt_scope;
1772 {
1773 MutexLocker ml(current, Compile_lock);
1774
1775 set_init_state(InstanceKlass::loaded);
1776 // make sure init_state store is already done.
1777 // The compiler reads the hierarchy outside of the Compile_lock.
1778 // Access ordering is used to add to hierarchy.
1779
1780 // Link into hierarchy.
1781 append_to_sibling_list(); // add to superklass/sibling list
1782 process_interfaces(); // handle all "implements" declarations
1783
1784 // Now mark all code that depended on old class hierarchy.
1785 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1996 : vmSymbols::java_lang_IllegalAccessException(), external_name());
1997 }
1998 }
1999
2000 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
2001 // Need load-acquire for lock-free read
2002 if (array_klasses_acquire() == nullptr) {
2003
2004 // Recursively lock array allocation
2005 RecursiveLocker rl(MultiArray_lock, THREAD);
2006
2007 // Check if another thread created the array klass while we were waiting for the lock.
2008 if (array_klasses() == nullptr) {
2009 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
2010 // use 'release' to pair with lock-free load
2011 release_set_array_klasses(k);
2012 }
2013 }
2014
2015 // array_klasses() will always be set at this point
2016 ArrayKlass* ak = array_klasses();
2017 assert(ak != nullptr, "should be set");
2018 return ak->array_klass(n, THREAD);
2019 }
2020
2021 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
2022 // Need load-acquire for lock-free read
2023 ArrayKlass* ak = array_klasses_acquire();
2024 if (ak == nullptr) {
2025 return nullptr;
2026 } else {
2027 return ak->array_klass_or_null(n);
2028 }
2029 }
2030
2031 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
2032 return array_klass(1, THREAD);
2033 }
2034
2035 ArrayKlass* InstanceKlass::array_klass_or_null() {
2036 return array_klass_or_null(1);
2037 }
2038
2039 Method* InstanceKlass::class_initializer() const {
2040 Method* clinit = find_method(
2041 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
2042 if (clinit != nullptr && clinit->is_class_initializer()) {
2043 return clinit;
2044 }
2045 return nullptr;
2046 }
2047
2048 void InstanceKlass::call_class_initializer(TRAPS) {
2049 if (ReplayCompiles &&
2050 (ReplaySuppressInitializers == 1 ||
2051 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
2052 // Hide the existence of the initializer for the purpose of replaying the compile
2053 return;
2054 }
2055
2056 #if INCLUDE_CDS
2057 // This is needed to ensure the consistency of the archived heap objects.
2058 if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
2059 AOTClassInitializer::call_runtime_setup(THREAD, this);
2060 return;
2061 } else if (has_archived_enum_objs()) {
2062 assert(in_aot_cache(), "must be");
2131
2132 void InstanceKlass::mask_for(const methodHandle& method, int bci,
2133 InterpreterOopMap* entry_for) {
2134 // Lazily create the _oop_map_cache at first request.
2135 // Load_acquire is needed to safely get instance published with CAS by another thread.
2136 OopMapCache* oop_map_cache = AtomicAccess::load_acquire(&_oop_map_cache);
2137 if (oop_map_cache == nullptr) {
2138 // Try to install new instance atomically.
2139 oop_map_cache = new OopMapCache();
2140 OopMapCache* other = AtomicAccess::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
2141 if (other != nullptr) {
2142 // Someone else managed to install before us, ditch local copy and use the existing one.
2143 delete oop_map_cache;
2144 oop_map_cache = other;
2145 }
2146 }
2147 // _oop_map_cache is constant after init; lookup below does its own locking.
2148 oop_map_cache->lookup(method, bci, entry_for);
2149 }
2150
2151
2152 FieldInfo InstanceKlass::field(int index) const {
2153 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2154 if (fs.index() == index) {
2155 return fs.to_FieldInfo();
2156 }
2157 }
2158 fatal("Field not found");
2159 return FieldInfo();
2160 }
2161
2162 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
2163 JavaFieldStream fs(this);
2164 if (fs.lookup(name, sig)) {
2165 assert(fs.name() == name, "name must match");
2166 assert(fs.signature() == sig, "signature must match");
2167 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2168 return true;
2169 }
2170 return false;
2211
2212 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
2213 // search order according to newest JVM spec (5.4.3.2, p.167).
2214 // 1) search for field in current klass
2215 if (find_local_field(name, sig, fd)) {
2216 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
2217 }
2218 // 2) search for field recursively in direct superinterfaces
2219 if (is_static) {
2220 Klass* intf = find_interface_field(name, sig, fd);
2221 if (intf != nullptr) return intf;
2222 }
2223 // 3) apply field lookup recursively if superclass exists
2224 { InstanceKlass* supr = super();
2225 if (supr != nullptr) return supr->find_field(name, sig, is_static, fd);
2226 }
2227 // 4) otherwise field lookup fails
2228 return nullptr;
2229 }
2230
2231 bool InstanceKlass::contains_field_offset(int offset) {
2232 if (this->is_inline_klass()) {
2233 InlineKlass* vk = InlineKlass::cast(this);
2234 return offset >= vk->payload_offset() && offset < (vk->payload_offset() + vk->payload_size_in_bytes());
2235 } else {
2236 fieldDescriptor fd;
2237 return find_field_from_offset(offset, false, &fd);
2238 }
2239 }
2240
2241 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2242 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2243 if (fs.offset() == offset) {
2244 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2245 if (fd->is_static() == is_static) return true;
2246 }
2247 }
2248 return false;
2249 }
2250
2251
2252 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2253 const InstanceKlass* klass = this;
2254 while (klass != nullptr) {
2255 if (klass->find_local_field_from_offset(offset, is_static, fd)) {
2256 return true;
2257 }
2258 klass = klass->super();
2259 }
2260 return false;
2261 }
2262
2263 bool InstanceKlass::find_local_flat_field_containing_offset(int offset, fieldDescriptor* fd) const {
2264 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2265 if (!fs.is_flat()) {
2266 continue;
2267 }
2268
2269 if (fs.offset() > offset) {
2270 continue;
2271 }
2272
2273 const int offset_in_flat_field = offset - fs.offset();
2274 const InlineLayoutInfo layout_info = inline_layout_info(fs.index());
2275 const int field_size = layout_info.klass()->layout_size_in_bytes(layout_info.kind());
2276
2277 assert(LayoutKindHelper::is_flat(layout_info.kind()), "Must be flat");
2278
2279 if (offset_in_flat_field < field_size) {
2280 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2281 assert(!fd->is_static(), "Static fields are not flattened");
2282
2283 return true;
2284 }
2285 }
2286
2287 return false;
2288 }
2289
2290 bool InstanceKlass::find_flat_field_containing_offset(int offset, fieldDescriptor* fd) const {
2291 const InstanceKlass* klass = this;
2292 while (klass != nullptr) {
2293 if (klass->find_local_flat_field_containing_offset(offset, fd)) {
2294 return true;
2295 }
2296
2297 klass = klass->super();
2298 }
2299
2300 return false;
2301 }
2302
2303 void InstanceKlass::methods_do(void f(Method* method)) {
2304 // Methods aren't stable until they are loaded. This can be read outside
2305 // a lock through the ClassLoaderData for profiling
2306 // Redefined scratch classes are on the list and need to be cleaned
2307 if (!is_loaded() && !is_scratch_class()) {
2308 return;
2309 }
2310
2311 int len = methods()->length();
2312 for (int index = 0; index < len; index++) {
2313 Method* m = methods()->at(index);
2314 assert(m->is_method(), "must be method");
2315 f(m);
2316 }
2317 }
2318
2319
2320 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
2321 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2322 if (fs.access_flags().is_static()) {
2323 fieldDescriptor& fd = fs.field_descriptor();
2324 cl->do_field(&fd);
2325 }
2326 }
2327 }
2328
2329
2330 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
2331 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2332 if (fs.access_flags().is_static()) {
2333 fieldDescriptor& fd = fs.field_descriptor();
2334 f(&fd, mirror, CHECK);
2335 }
2336 }
2337 }
2338
2339 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
2340 InstanceKlass* super = this->super();
2341 if (super != nullptr) {
2342 super->do_nonstatic_fields(cl);
2343 }
2344 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2345 fieldDescriptor& fd = fs.field_descriptor();
2346 if (!fd.is_static()) {
2347 cl->do_field(&fd);
2348 }
2349 }
2350 }
2351
2642 }
2643
2644 // uncached_lookup_method searches both the local class methods array and all
2645 // superclasses methods arrays, skipping any overpass methods in superclasses,
2646 // and possibly skipping private methods.
2647 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2648 const Symbol* signature,
2649 OverpassLookupMode overpass_mode,
2650 PrivateLookupMode private_mode) const {
2651 OverpassLookupMode overpass_local_mode = overpass_mode;
2652 const InstanceKlass* klass = this;
2653 while (klass != nullptr) {
2654 Method* const method = klass->find_method_impl(name,
2655 signature,
2656 overpass_local_mode,
2657 StaticLookupMode::find,
2658 private_mode);
2659 if (method != nullptr) {
2660 return method;
2661 }
2662 if (name == vmSymbols::object_initializer_name()) {
2663 break; // <init> is never inherited
2664 }
2665 klass = klass->super();
2666 overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses
2667 }
2668 return nullptr;
2669 }
2670
2671 #ifdef ASSERT
2672 // search through class hierarchy and return true if this class or
2673 // one of the superclasses was redefined
2674 bool InstanceKlass::has_redefined_this_or_super() const {
2675 const InstanceKlass* klass = this;
2676 while (klass != nullptr) {
2677 if (klass->has_been_redefined()) {
2678 return true;
2679 }
2680 klass = klass->super();
2681 }
2682 return false;
2683 }
2684 #endif
3057 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
3058
3059 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
3060 / itableOffsetEntry::size();
3061
3062 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
3063 if (ioe->interface_klass() != nullptr) {
3064 it->push(ioe->interface_klass_addr());
3065 itableMethodEntry* ime = ioe->first_method_entry(this);
3066 int n = klassItable::method_count_for_interface(ioe->interface_klass());
3067 for (int index = 0; index < n; index ++) {
3068 it->push(ime[index].method_addr());
3069 }
3070 }
3071 }
3072 }
3073
3074 it->push(&_nest_host);
3075 it->push(&_nest_members);
3076 it->push(&_permitted_subclasses);
3077 it->push(&_loadable_descriptors);
3078 it->push(&_acmp_maps_array, MetaspaceClosure::_writable);
3079 it->push(&_record_components);
3080 it->push(&_inline_layout_info_array, MetaspaceClosure::_writable);
3081
3082 if (CDSConfig::is_dumping_full_module_graph() && !defined_by_other_loaders()) {
3083 it->push(&_package_entry);
3084 }
3085 }
3086
3087 #if INCLUDE_CDS
3088 void InstanceKlass::remove_unshareable_info() {
3089
3090 if (is_linked()) {
3091 assert(can_be_verified_at_dumptime(), "must be");
3092 // Remember this so we can avoid walking the hierarchy at runtime.
3093 set_verified_at_dump_time();
3094 }
3095
3096 _misc_flags.set_has_init_deps_processed(false);
3097
3098 Klass::remove_unshareable_info();
3099
3100 if (SystemDictionaryShared::has_class_failed_verification(this)) {
3112
3113 { // Otherwise this needs to take out the Compile_lock.
3114 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
3115 init_implementor();
3116 }
3117
3118 // Call remove_unshareable_info() on other objects that belong to this class, except
3119 // for constants()->remove_unshareable_info(), which is called in a separate pass in
3120 // ArchiveBuilder::make_klasses_shareable(),
3121
3122 for (int i = 0; i < methods()->length(); i++) {
3123 Method* m = methods()->at(i);
3124 m->remove_unshareable_info();
3125 }
3126
3127 // do array classes also.
3128 if (array_klasses() != nullptr) {
3129 array_klasses()->remove_unshareable_info();
3130 }
3131
3132 // These are not allocated from metaspace. They are safe to set to nullptr.
3133 _source_debug_extension = nullptr;
3134 _dep_context = nullptr;
3135 _osr_nmethods_head = nullptr;
3136 #if INCLUDE_JVMTI
3137 _breakpoints = nullptr;
3138 _previous_versions = nullptr;
3139 _cached_class_file = nullptr;
3140 _jvmti_cached_class_field_map = nullptr;
3141 #endif
3142
3143 _init_thread = nullptr;
3144 _methods_jmethod_ids = nullptr;
3145 _jni_ids = nullptr;
3146 _oop_map_cache = nullptr;
3147 if (CDSConfig::is_dumping_method_handles() && HeapShared::is_lambda_proxy_klass(this)) {
3148 // keep _nest_host
3149 } else {
3150 // clear _nest_host to ensure re-load at runtime
3151 _nest_host = nullptr;
3152 }
3188 void InstanceKlass::compute_has_loops_flag_for_methods() {
3189 Array<Method*>* methods = this->methods();
3190 for (int index = 0; index < methods->length(); ++index) {
3191 Method* m = methods->at(index);
3192 if (!m->is_overpass()) { // work around JDK-8305771
3193 m->compute_has_loops_flag();
3194 }
3195 }
3196 }
3197
3198 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
3199 PackageEntry* pkg_entry, TRAPS) {
3200 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
3201 // before the InstanceKlass is added to the SystemDictionary. Make
3202 // sure the current state is <loaded.
3203 assert(!is_loaded(), "invalid init state");
3204 assert(!shared_loading_failed(), "Must not try to load failed class again");
3205 set_package(loader_data, pkg_entry, CHECK);
3206 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
3207
3208 if (is_inline_klass()) {
3209 InlineKlass::cast(this)->initialize_calling_convention(CHECK);
3210 }
3211
3212 Array<Method*>* methods = this->methods();
3213 int num_methods = methods->length();
3214 for (int index = 0; index < num_methods; ++index) {
3215 methods->at(index)->restore_unshareable_info(CHECK);
3216 }
3217 #if INCLUDE_JVMTI
3218 if (JvmtiExport::has_redefined_a_class()) {
3219 // Reinitialize vtable because RedefineClasses may have changed some
3220 // entries in this vtable for super classes so the CDS vtable might
3221 // point to old or obsolete entries. RedefineClasses doesn't fix up
3222 // vtables in the shared system dictionary, only the main one.
3223 // It also redefines the itable too so fix that too.
3224 // First fix any default methods that point to a super class that may
3225 // have been redefined.
3226 bool trace_name_printed = false;
3227 adjust_default_methods(&trace_name_printed);
3228 if (verified_at_dump_time()) {
3229 // Initialize vtable and itable for classes which can be verified at dump time.
3230 // Unlinked classes such as old classes with major version < 50 cannot be verified
3231 // at dump time.
3232 vtable().initialize_vtable();
3233 itable().initialize_itable();
3234 }
3235 }
3236 #endif // INCLUDE_JVMTI
3237
3238 // restore constant pool resolved references
3239 constants()->restore_unshareable_info(CHECK);
3240
3241 // Restore acmp_maps java array from the version stored in metadata.
3242 // if it cannot be found in the archive
3243 if (Arguments::is_valhalla_enabled() && has_acmp_maps_offset() && java_mirror()->obj_field(_acmp_maps_offset) == nullptr) {
3244 int acmp_maps_size = _acmp_maps_array->length();
3245 typeArrayOop map = oopFactory::new_intArray(acmp_maps_size, CHECK);
3246 typeArrayHandle map_h(THREAD, map);
3247 for (int i = 0; i < acmp_maps_size; i++) {
3248 map_h->int_at_put(i, _acmp_maps_array->at(i));
3249 }
3250 java_mirror()->obj_field_put(_acmp_maps_offset, map_h());
3251 }
3252
3253 if (array_klasses() != nullptr) {
3254 // To get a consistent list of classes we need MultiArray_lock to ensure
3255 // array classes aren't observed while they are being restored.
3256 RecursiveLocker rl(MultiArray_lock, THREAD);
3257 assert(this == ObjArrayKlass::cast(array_klasses())->bottom_klass(), "sanity");
3258 // Array classes have null protection domain.
3259 // --> see ArrayKlass::complete_create_array_klass()
3260 if (class_loader_data() == nullptr) {
3261 ResourceMark rm(THREAD);
3262 log_debug(cds)(" loader_data %s ", loader_data == nullptr ? "nullptr" : "non null");
3263 log_debug(cds)(" this %s array_klasses %s ", this->name()->as_C_string(), array_klasses()->name()->as_C_string());
3264 }
3265 assert(!array_klasses()->is_refined_objArray_klass(), "must be non-refined objarrayklass");
3266 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
3267 }
3268
3269 // Initialize @ValueBased class annotation if not already set in the archived klass.
3270 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
3271 set_is_value_based();
3272 }
3273
3274 DEBUG_ONLY(FieldInfoStream::validate_search_table(_constants, _fieldinfo_stream, _fieldinfo_search_table));
3275 }
3276
3277 bool InstanceKlass::can_be_verified_at_dumptime() const {
3278 if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(this)) {
3279 // This is a class that was dumped into the base archive, so we know
3280 // it was verified at dump time.
3281 return true;
3282 }
3283
3284 if (CDSConfig::is_preserving_verification_constraints()) {
3285 return true;
3401 constants()->release_C_heap_structures();
3402 }
3403 }
3404
3405 // The constant pool is on stack if any of the methods are executing or
3406 // referenced by handles.
3407 bool InstanceKlass::on_stack() const {
3408 return _constants->on_stack();
3409 }
3410
3411 Symbol* InstanceKlass::source_file_name() const { return _constants->source_file_name(); }
3412 u2 InstanceKlass::source_file_name_index() const { return _constants->source_file_name_index(); }
3413 void InstanceKlass::set_source_file_name_index(u2 sourcefile_index) { _constants->set_source_file_name_index(sourcefile_index); }
3414
3415 // minor and major version numbers of class file
3416 u2 InstanceKlass::minor_version() const { return _constants->minor_version(); }
3417 void InstanceKlass::set_minor_version(u2 minor_version) { _constants->set_minor_version(minor_version); }
3418 u2 InstanceKlass::major_version() const { return _constants->major_version(); }
3419 void InstanceKlass::set_major_version(u2 major_version) { _constants->set_major_version(major_version); }
3420
3421 bool InstanceKlass::supports_inline_types() const {
3422 return major_version() >= Verifier::VALUE_TYPES_MAJOR_VERSION && minor_version() == Verifier::JAVA_PREVIEW_MINOR_VERSION;
3423 }
3424
3425 const InstanceKlass* InstanceKlass::get_klass_version(int version) const {
3426 for (const InstanceKlass* ik = this; ik != nullptr; ik = ik->previous_versions()) {
3427 if (ik->constants()->version() == version) {
3428 return ik;
3429 }
3430 }
3431 return nullptr;
3432 }
3433
3434 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
3435 if (array == nullptr) {
3436 _source_debug_extension = nullptr;
3437 } else {
3438 // Adding one to the attribute length in order to store a null terminator
3439 // character could cause an overflow because the attribute length is
3440 // already coded with an u4 in the classfile, but in practice, it's
3441 // unlikely to happen.
3442 assert((length+1) > length, "Overflow checking");
3443 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
3444 for (int i = 0; i < length; i++) {
3445 sde[i] = array[i];
3446 }
3447 sde[length] = '\0';
3448 _source_debug_extension = sde;
3449 }
3450 }
3451
3452 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); }
3453 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); }
3454 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); }
3455
3456 const char* InstanceKlass::signature_name() const {
3457 return signature_name_of_carrier(JVM_SIGNATURE_CLASS);
3458 }
3459
3460 const char* InstanceKlass::signature_name_of_carrier(char c) const {
3461 // Get the internal name as a c string
3462 const char* src = (const char*) (name()->as_C_string());
3463 const int src_length = (int)strlen(src);
3464
3465 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
3466
3467 // Add L or Q as type indicator
3468 int dest_index = 0;
3469 dest[dest_index++] = c;
3470
3471 // Add the actual class name
3472 for (int src_index = 0; src_index < src_length; ) {
3473 dest[dest_index++] = src[src_index++];
3474 }
3475
3476 if (is_hidden()) { // Replace the last '+' with a '.'.
3477 for (int index = (int)src_length; index > 0; index--) {
3478 if (dest[index] == '+') {
3479 dest[index] = JVM_SIGNATURE_DOT;
3480 break;
3481 }
3482 }
3483 }
3484
3485 // Add the semicolon and the null
3486 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3487 dest[dest_index] = '\0';
3488 return dest;
3489 }
3730 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3731 constantPoolHandle i_cp(THREAD, constants());
3732 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3733 int ioff = iter.inner_class_info_index();
3734 if (ioff != 0) {
3735 // Check to see if the name matches the class we're looking for
3736 // before attempting to find the class.
3737 if (i_cp->klass_name_at_matches(this, ioff)) {
3738 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3739 if (this == inner_klass) {
3740 *ooff = iter.outer_class_info_index();
3741 *noff = iter.inner_name_index();
3742 return true;
3743 }
3744 }
3745 }
3746 }
3747 return false;
3748 }
3749
3750 void InstanceKlass::check_can_be_annotated_with_NullRestricted(InstanceKlass* type, Symbol* container_klass_name, TRAPS) {
3751 assert(type->is_instance_klass(), "Sanity check");
3752 if (type->is_identity_class()) {
3753 ResourceMark rm(THREAD);
3754 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
3755 err_msg("Class %s expects class %s to be a value class, but it is an identity class",
3756 container_klass_name->as_C_string(),
3757 type->external_name()));
3758 }
3759
3760 if (type->is_abstract()) {
3761 ResourceMark rm(THREAD);
3762 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
3763 err_msg("Class %s expects class %s to be concrete value type, but it is an abstract class",
3764 container_klass_name->as_C_string(),
3765 type->external_name()));
3766 }
3767 }
3768
3769 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3770 InstanceKlass* outer_klass = nullptr;
3771 *inner_is_member = false;
3772 int ooff = 0, noff = 0;
3773 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3774 if (has_inner_classes_attr) {
3775 constantPoolHandle i_cp(THREAD, constants());
3776 if (ooff != 0) {
3777 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3778 if (!ok->is_instance_klass()) {
3779 // If the outer class is not an instance klass then it cannot have
3780 // declared any inner classes.
3781 ResourceMark rm(THREAD);
3782 // Names are all known to be < 64k so we know this formatted message is not excessively large.
3783 Exceptions::fthrow(
3784 THREAD_AND_LOCATION,
3785 vmSymbols::java_lang_IncompatibleClassChangeError(),
3786 "%s and %s disagree on InnerClasses attribute",
3787 ok->external_name(),
3788 external_name());
3815 u2 InstanceKlass::compute_modifier_flags() const {
3816 u2 access = access_flags().as_unsigned_short();
3817
3818 // But check if it happens to be member class.
3819 InnerClassesIterator iter(this);
3820 for (; !iter.done(); iter.next()) {
3821 int ioff = iter.inner_class_info_index();
3822 // Inner class attribute can be zero, skip it.
3823 // Strange but true: JVM spec. allows null inner class refs.
3824 if (ioff == 0) continue;
3825
3826 // only look at classes that are already loaded
3827 // since we are looking for the flags for our self.
3828 Symbol* inner_name = constants()->klass_name_at(ioff);
3829 if (name() == inner_name) {
3830 // This is really a member class.
3831 access = iter.inner_access_flags();
3832 break;
3833 }
3834 }
3835 if (!Arguments::is_valhalla_enabled()) {
3836 // Remember to strip ACC_SUPER bit without Valhalla
3837 access &= (~JVM_ACC_SUPER);
3838 }
3839 return access;
3840 }
3841
3842 jint InstanceKlass::jvmti_class_status() const {
3843 jint result = 0;
3844
3845 if (is_linked()) {
3846 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3847 }
3848
3849 if (is_initialized()) {
3850 assert(is_linked(), "Class status is not consistent");
3851 result |= JVMTI_CLASS_STATUS_INITIALIZED;
3852 }
3853 if (is_in_error_state()) {
3854 result |= JVMTI_CLASS_STATUS_ERROR;
3855 }
3856 return result;
3857 }
3858
3859 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
4073 }
4074 osr = osr->osr_link();
4075 }
4076
4077 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
4078 if (best != nullptr && best->comp_level() >= comp_level) {
4079 return best;
4080 }
4081 return nullptr;
4082 }
4083
4084 // -----------------------------------------------------------------------------------------------------
4085 // Printing
4086
4087 #define BULLET " - "
4088
4089 static const char* state_names[] = {
4090 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
4091 };
4092
4093 static void print_vtable(address self, intptr_t* start, int len, outputStream* st) {
4094 ResourceMark rm;
4095 int* forward_refs = NEW_RESOURCE_ARRAY(int, len);
4096 for (int i = 0; i < len; i++) forward_refs[i] = 0;
4097 for (int i = 0; i < len; i++) {
4098 intptr_t e = start[i];
4099 st->print("%d : " INTPTR_FORMAT, i, e);
4100 if (forward_refs[i] != 0) {
4101 int from = forward_refs[i];
4102 int off = (int) start[from];
4103 st->print(" (offset %d <= [%d])", off, from);
4104 }
4105 if (MetaspaceObj::is_valid((Metadata*)e)) {
4106 st->print(" ");
4107 ((Metadata*)e)->print_value_on(st);
4108 } else if (self != nullptr && e > 0 && e < 0x10000) {
4109 address location = self + e;
4110 int index = (int)((intptr_t*)location - start);
4111 st->print(" (offset %d => [%d])", (int)e, index);
4112 if (index >= 0 && index < len)
4113 forward_refs[index] = i;
4114 }
4115 st->cr();
4116 }
4117 }
4118
4119 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
4120 return print_vtable(nullptr, reinterpret_cast<intptr_t*>(start), len, st);
4121 }
4122
4123 const char* InstanceKlass::init_state_name() const {
4124 return state_names[init_state()];
4125 }
4126
4127 void InstanceKlass::print_on(outputStream* st) const {
4128 assert(is_klass(), "must be klass");
4129 Klass::print_on(st);
4130
4131 st->print(BULLET"instance size: %d", size_helper()); st->cr();
4132 st->print(BULLET"klass size: %d", size()); st->cr();
4133 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
4134 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
4135 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
4136 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
4137 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
4138 st->print(BULLET"sub: ");
4139 Klass* sub = subklass();
4140 int n;
4141 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
4142 if (n < MaxSubklassPrintSize) {
4143 sub->print_value_on(st);
4144 st->print(" ");
4145 }
4146 }
4147 if (n >= MaxSubklassPrintSize) st->print("(%zd more klasses...)", n - MaxSubklassPrintSize);
4148 st->cr();
4149
4150 if (is_interface()) {
4151 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
4152 if (nof_implementors() == 1) {
4153 st->print_cr(BULLET"implementor: ");
4154 st->print(" ");
4155 implementor()->print_value_on(st);
4156 st->cr();
4157 }
4158 }
4159
4160 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
4161 st->print(BULLET"methods: ");
4162 print_array_on(st, methods(), [](outputStream* ost, Method* method) {
4163 method->print_value_on(ost);
4164 });
4165 st->print(BULLET"method ordering: ");
4166 print_array_on(st, method_ordering(), [](outputStream* ost, int i) {
4167 ost->print("%d", i);
4168 });
4169 if (default_methods() != nullptr) {
4170 st->print(BULLET"default_methods: ");
4171 print_array_on(st, default_methods(), [](outputStream* ost, Method* method) {
4172 method->print_value_on(ost);
4173 });
4174 }
4175 print_on_maybe_null(st, BULLET"default vtable indices: ", default_vtable_indices());
4176 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
4177 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
4178
4179 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr();
4180
4181 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr();
4182 st->print(BULLET"secondary bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap); st->cr();
4183
4184 if (secondary_supers() != nullptr) {
4185 if (Verbose) {
4186 bool is_hashed = (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL);
4187 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length());
4188 for (int i = 0; i < _secondary_supers->length(); i++) {
4189 ResourceMark rm; // for external_name()
4190 Klass* secondary_super = _secondary_supers->at(i);
4191 st->print(BULLET"%2d:", i);
4192 if (is_hashed) {
4193 int home_slot = compute_home_slot(secondary_super, _secondary_supers_bitmap);
4194 int distance = (i - home_slot) & SECONDARY_SUPERS_TABLE_MASK;
4195 st->print(" dist:%02d:", distance);
4196 }
4197 st->print_cr(" %p %s", secondary_super, secondary_super->external_name());
4198 }
4199 }
4200 }
4201 st->print(BULLET"constants: "); constants()->print_value_on(st); st->cr();
4202
4203 print_on_maybe_null(st, BULLET"class loader data: ", class_loader_data());
4204 print_on_maybe_null(st, BULLET"source file: ", source_file_name());
4205 if (source_debug_extension() != nullptr) {
4206 st->print(BULLET"source debug extension: ");
4207 st->print("%s", source_debug_extension());
4208 st->cr();
4209 }
4210 print_on_maybe_null(st, BULLET"class annotations: ", class_annotations());
4211 print_on_maybe_null(st, BULLET"class type annotations: ", class_type_annotations());
4212 print_on_maybe_null(st, BULLET"field annotations: ", fields_annotations());
4213 print_on_maybe_null(st, BULLET"field type annotations: ", fields_type_annotations());
4214 {
4215 bool have_pv = false;
4216 // previous versions are linked together through the InstanceKlass
4217 for (InstanceKlass* pv_node = previous_versions();
4218 pv_node != nullptr;
4219 pv_node = pv_node->previous_versions()) {
4220 if (!have_pv)
4221 st->print(BULLET"previous version: ");
4222 have_pv = true;
4223 pv_node->constants()->print_value_on(st);
4224 }
4225 if (have_pv) st->cr();
4226 }
4227
4228 print_on_maybe_null(st, BULLET"generic signature: ", generic_signature());
4229 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
4230 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();
4231 print_on_maybe_null(st, BULLET"record components: ", record_components());
4232 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();
4233 st->print(BULLET"loadable descriptors: "); loadable_descriptors()->print_value_on(st); st->cr();
4234 if (java_mirror() != nullptr) {
4235 st->print(BULLET"java mirror: ");
4236 java_mirror()->print_value_on(st);
4237 st->cr();
4238 } else {
4239 st->print_cr(BULLET"java mirror: null");
4240 }
4241 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
4242 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);
4243 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
4244 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(nullptr, start_of_itable(), itable_length(), st);
4245
4246 InstanceKlass* ik = const_cast<InstanceKlass*>(this);
4247 // There is no oop so static and nonstatic printing can use the same printer.
4248 FieldPrinter field_printer(st);
4249 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
4250 ik->do_local_static_fields(&field_printer);
4251 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
4252 ik->print_nonstatic_fields(&field_printer);
4253
4254 st->print(BULLET"non-static oop maps (%d entries): ", nonstatic_oop_map_count());
4255 OopMapBlock* map = start_of_nonstatic_oop_maps();
4256 OopMapBlock* end_map = map + nonstatic_oop_map_count();
4257 while (map < end_map) {
4258 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
4259 map++;
4260 }
4261 st->cr();
4262
4263 if (fieldinfo_search_table() != nullptr) {
4264 st->print_cr(BULLET"---- field info search table:");
4265 FieldInfoStream::print_search_table(st, _constants, _fieldinfo_stream, _fieldinfo_search_table);
4266 }
4267 }
4268
4269 void InstanceKlass::print_value_on(outputStream* st) const {
4270 assert(is_klass(), "must be klass");
4271 if (Verbose || WizardMode) access_flags().print_on(st);
4272 name()->print_value_on(st);
4273 }
4274
4275 void FieldPrinter::do_field(fieldDescriptor* fd) {
4276 for (int i = 0; i < _indent; i++) _st->print(" ");
4277 _st->print(BULLET);
4278 // Handles the cases of static fields or instance fields but no oop is given.
4279 if (_obj == nullptr) {
4280 fd->print_on(_st, _base_offset);
4281 _st->cr();
4282 } else {
4283 fd->print_on_for(_st, _obj, _indent, _base_offset);
4284 if (!fd->field_flags().is_flat()) _st->cr();
4285 }
4286 }
4287
4288
4289 void InstanceKlass::oop_print_on(oop obj, outputStream* st, int indent, int base_offset) {
4290 Klass::oop_print_on(obj, st);
4291
4292 if (this == vmClasses::String_klass()) {
4293 typeArrayOop value = java_lang_String::value(obj);
4294 juint length = java_lang_String::length(obj);
4295 if (value != nullptr &&
4296 value->is_typeArray() &&
4297 length <= (juint) value->length()) {
4298 st->print(BULLET"string: ");
4299 java_lang_String::print(obj, st);
4300 st->cr();
4301 }
4302 }
4303
4304 st->print_cr(BULLET"---- fields (total size %zu words):", oop_size(obj));
4305 FieldPrinter print_field(st, obj, indent, base_offset);
4306 print_nonstatic_fields(&print_field);
4307
4308 if (this == vmClasses::Class_klass()) {
4309 st->print(BULLET"signature: ");
4310 java_lang_Class::print_signature(obj, st);
4311 st->cr();
4312 Klass* real_klass = java_lang_Class::as_Klass(obj);
4313 if (real_klass != nullptr && real_klass->is_instance_klass()) {
4314 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj));
4315 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
4316 }
4317 } else if (this == vmClasses::MethodType_klass()) {
4318 st->print(BULLET"signature: ");
4319 java_lang_invoke_MethodType::print_signature(obj, st);
4320 st->cr();
4321 }
4322 }
4323
4324 #ifndef PRODUCT
4325
|