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);
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 bool InstanceKlass::_finalization_enabled = true;
183 static int call_class_initializer_counter = 0; // for debugging
184
185 static inline bool is_class_loader(const Symbol* class_name,
186 const ClassFileParser& parser) {
187 assert(class_name != nullptr, "invariant");
188
189 if (class_name == vmSymbols::java_lang_ClassLoader()) {
190 return true;
191 }
192
193 if (vmClasses::ClassLoader_klass_is_loaded()) {
194 const Klass* const super_klass = parser.super_klass();
195 if (super_klass != nullptr) {
196 if (super_klass->is_subtype_of(vmClasses::ClassLoader_klass())) {
197 return true;
198 }
199 }
200 }
201 return false;
202 }
203
204 bool InstanceKlass::field_is_null_free_inline_type(int index) const {
205 return field(index).field_flags().is_null_free_inline_type();
206 }
207
208 bool InstanceKlass::is_class_in_loadable_descriptors_attribute(Symbol* name) const {
209 if (_loadable_descriptors == nullptr) return false;
210 for (int i = 0; i < _loadable_descriptors->length(); i++) {
211 Symbol* class_name = _constants->symbol_at(_loadable_descriptors->at(i));
212 if (class_name == name) return true;
213 }
214 return false;
215 }
216
217 static inline bool is_stack_chunk_class(const Symbol* class_name,
218 const ClassLoaderData* loader_data) {
219 return (class_name == vmSymbols::jdk_internal_vm_StackChunk() &&
220 loader_data->is_the_null_class_loader_data());
221 }
222
223 // private: called to verify that k is a static member of this nest.
224 // We know that k is an instance class in the same package and hence the
225 // same classloader.
226 bool InstanceKlass::has_nest_member(JavaThread* current, InstanceKlass* k) const {
227 assert(!is_hidden(), "unexpected hidden class");
228 if (_nest_members == nullptr || _nest_members == Universe::the_empty_short_array()) {
229 if (log_is_enabled(Trace, class, nestmates)) {
230 ResourceMark rm(current);
231 log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
232 k->external_name(), this->external_name());
233 }
234 return false;
235 }
236
484 log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
485 this->external_name(),
486 access ? "" : "NOT ",
487 k->external_name());
488 return access;
489 }
490
491 const char* InstanceKlass::nest_host_error() {
492 if (_nest_host_index == 0) {
493 return nullptr;
494 } else {
495 constantPoolHandle cph(Thread::current(), constants());
496 return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index);
497 }
498 }
499
500 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
501 const int size = InstanceKlass::size(parser.vtable_size(),
502 parser.itable_size(),
503 nonstatic_oop_map_size(parser.total_oop_map_count()),
504 parser.is_interface(),
505 parser.is_inline_type());
506
507 const Symbol* const class_name = parser.class_name();
508 assert(class_name != nullptr, "invariant");
509 ClassLoaderData* loader_data = parser.loader_data();
510 assert(loader_data != nullptr, "invariant");
511
512 InstanceKlass* ik;
513
514 // Allocation
515 if (parser.is_instance_ref_klass()) {
516 // java.lang.ref.Reference
517 ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
518 } else if (class_name == vmSymbols::java_lang_Class()) {
519 // mirror - java.lang.Class
520 ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
521 } else if (is_stack_chunk_class(class_name, loader_data)) {
522 // stack chunk
523 ik = new (loader_data, size, THREAD) InstanceStackChunkKlass(parser);
524 } else if (is_class_loader(class_name, parser)) {
525 // class loader - java.lang.ClassLoader
526 ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);
527 } else if (parser.is_inline_type()) {
528 // inline type
529 ik = new (loader_data, size, THREAD) InlineKlass(parser);
530 } else {
531 // normal
532 ik = new (loader_data, size, THREAD) InstanceKlass(parser);
533 }
534
535 assert(ik == nullptr || CompressedKlassPointers::is_encodable(ik),
536 "Klass " PTR_FORMAT "needs a narrow Klass ID, but is not encodable", p2i(ik));
537
538 // Check for pending exception before adding to the loader data and incrementing
539 // class count. Can get OOM here.
540 if (HAS_PENDING_EXCEPTION) {
541 return nullptr;
542 }
543
544 #ifdef ASSERT
545 ik->bounds_check((address) ik->start_of_vtable(), false, size);
546 ik->bounds_check((address) ik->start_of_itable(), false, size);
547 ik->bounds_check((address) ik->end_of_itable(), true, size);
548 ik->bounds_check((address) ik->end_of_nonstatic_oop_maps(), true, size);
549 #endif //ASSERT
550 return ik;
551 }
552
553 #ifndef PRODUCT
554 bool InstanceKlass::bounds_check(address addr, bool edge_ok, intptr_t size_in_bytes) const {
555 const char* bad = nullptr;
556 address end = nullptr;
557 if (addr < (address)this) {
558 bad = "before";
559 } else if (addr == (address)this) {
560 if (edge_ok) return true;
561 bad = "just before";
562 } else if (addr == (end = (address)this + sizeof(intptr_t) * (size_in_bytes < 0 ? size() : size_in_bytes))) {
563 if (edge_ok) return true;
564 bad = "just after";
565 } else if (addr > end) {
566 bad = "after";
567 } else {
568 return true;
569 }
570 tty->print_cr("%s object bounds: " INTPTR_FORMAT " [" INTPTR_FORMAT ".." INTPTR_FORMAT "]",
571 bad, (intptr_t)addr, (intptr_t)this, (intptr_t)end);
572 Verbose = WizardMode = true; this->print(); //@@
573 return false;
574 }
575 #endif //PRODUCT
576
577 // copy method ordering from resource area to Metaspace
578 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
579 if (m != nullptr) {
580 // allocate a new array and copy contents (memcpy?)
581 _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
582 for (int i = 0; i < m->length(); i++) {
583 _method_ordering->at_put(i, m->at(i));
584 }
585 } else {
586 _method_ordering = Universe::the_empty_int_array();
587 }
588 }
589
590 // create a new array of vtable_indices for default methods
591 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
592 Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
593 assert(default_vtable_indices() == nullptr, "only create once");
594 set_default_vtable_indices(vtable_indices);
595 return vtable_indices;
596 }
597
598
599 InstanceKlass::InstanceKlass() {
600 assert(CDSConfig::is_dumping_static_archive() || CDSConfig::is_using_archive(), "only for CDS");
601 }
602
603 InstanceKlass::InstanceKlass(const ClassFileParser& parser, KlassKind kind, markWord prototype_header, ReferenceType reference_type) :
604 Klass(kind, prototype_header),
605 _nest_members(nullptr),
606 _nest_host(nullptr),
607 _permitted_subclasses(nullptr),
608 _record_components(nullptr),
609 _static_field_size(parser.static_field_size()),
610 _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
611 _itable_len(parser.itable_size()),
612 _nest_host_index(0),
613 _init_state(allocated),
614 _reference_type(reference_type),
615 _acmp_maps_offset(0),
616 _init_thread(nullptr),
617 _inline_layout_info_array(nullptr),
618 _loadable_descriptors(nullptr),
619 _acmp_maps_array(nullptr),
620 _adr_inline_klass_members(nullptr)
621 {
622 set_vtable_length(parser.vtable_size());
623 set_access_flags(parser.access_flags());
624 if (parser.is_hidden()) set_is_hidden();
625 set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
626 false));
627 if (parser.has_inlined_fields()) {
628 set_has_inlined_fields();
629 }
630
631 assert(nullptr == _methods, "underlying memory not zeroed?");
632 assert(is_instance_klass(), "is layout incorrect?");
633 assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
634 }
635
636 void InstanceKlass::set_is_cloneable() {
637 if (name() == vmSymbols::java_lang_invoke_MemberName()) {
638 assert(is_final(), "no subclasses allowed");
639 // MemberName cloning should not be intrinsified and always happen in JVM_Clone.
640 } else if (reference_type() != REF_NONE) {
641 // Reference cloning should not be intrinsified and always happen in JVM_Clone.
642 } else {
643 set_is_cloneable_fast();
644 }
645 }
646
647 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
648 Array<Method*>* methods) {
649 if (methods != nullptr && methods != Universe::the_empty_method_array() &&
765
766 deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
767 set_transitive_interfaces(nullptr);
768 set_local_interfaces(nullptr);
769
770 if (fieldinfo_stream() != nullptr && !fieldinfo_stream()->in_aot_cache()) {
771 MetadataFactory::free_array<u1>(loader_data, fieldinfo_stream());
772 }
773 set_fieldinfo_stream(nullptr);
774
775 if (fieldinfo_search_table() != nullptr && !fieldinfo_search_table()->in_aot_cache()) {
776 MetadataFactory::free_array<u1>(loader_data, fieldinfo_search_table());
777 }
778 set_fieldinfo_search_table(nullptr);
779
780 if (fields_status() != nullptr && !fields_status()->in_aot_cache()) {
781 MetadataFactory::free_array<FieldStatus>(loader_data, fields_status());
782 }
783 set_fields_status(nullptr);
784
785 if (inline_layout_info_array() != nullptr) {
786 MetadataFactory::free_array<InlineLayoutInfo>(loader_data, inline_layout_info_array());
787 }
788 set_inline_layout_info_array(nullptr);
789
790 // If a method from a redefined class is using this constant pool, don't
791 // delete it, yet. The new class's previous version will point to this.
792 if (constants() != nullptr) {
793 assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
794 if (!constants()->in_aot_cache()) {
795 HeapShared::remove_scratch_resolved_references(constants());
796 MetadataFactory::free_metadata(loader_data, constants());
797 }
798 // Delete any cached resolution errors for the constant pool
799 SystemDictionary::delete_resolution_error(constants());
800
801 set_constants(nullptr);
802 }
803
804 if (inner_classes() != nullptr &&
805 inner_classes() != Universe::the_empty_short_array() &&
806 !inner_classes()->in_aot_cache()) {
807 MetadataFactory::free_array<jushort>(loader_data, inner_classes());
808 }
809 set_inner_classes(nullptr);
810
811 if (nest_members() != nullptr &&
812 nest_members() != Universe::the_empty_short_array() &&
813 !nest_members()->in_aot_cache()) {
814 MetadataFactory::free_array<jushort>(loader_data, nest_members());
815 }
816 set_nest_members(nullptr);
817
818 if (permitted_subclasses() != nullptr &&
819 permitted_subclasses() != Universe::the_empty_short_array() &&
820 !permitted_subclasses()->in_aot_cache()) {
821 MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
822 }
823 set_permitted_subclasses(nullptr);
824
825 if (loadable_descriptors() != nullptr &&
826 loadable_descriptors() != Universe::the_empty_short_array() &&
827 !loadable_descriptors()->in_aot_cache()) {
828 MetadataFactory::free_array<jushort>(loader_data, loadable_descriptors());
829 }
830 set_loadable_descriptors(nullptr);
831
832 if (acmp_maps_array() != nullptr) {
833 MetadataFactory::free_array<int>(loader_data, acmp_maps_array());
834 }
835 set_acmp_maps_array(nullptr);
836
837 // We should deallocate the Annotations instance if it's not in shared spaces.
838 if (annotations() != nullptr && !annotations()->in_aot_cache()) {
839 MetadataFactory::free_metadata(loader_data, annotations());
840 }
841 set_annotations(nullptr);
842
843 SystemDictionaryShared::handle_class_unloading(this);
844
845 #if INCLUDE_CDS_JAVA_HEAP
846 if (CDSConfig::is_dumping_heap()) {
847 HeapShared::remove_scratch_objects(this);
848 }
849 #endif
850 }
851
852 bool InstanceKlass::is_record() const {
853 return _record_components != nullptr &&
854 is_final() &&
855 super() == vmClasses::Record_klass();
856 }
859 return _permitted_subclasses != nullptr &&
860 _permitted_subclasses != Universe::the_empty_short_array();
861 }
862
863 // JLS 8.9: An enum class is either implicitly final and derives
864 // from java.lang.Enum, or else is implicitly sealed to its
865 // anonymous subclasses. This query detects both kinds.
866 // It does not validate the finality or
867 // sealing conditions: it merely checks for a super of Enum.
868 // This is sufficient for recognizing well-formed enums.
869 bool InstanceKlass::is_enum_subclass() const {
870 InstanceKlass* s = super();
871 return (s == vmClasses::Enum_klass() ||
872 (s != nullptr && s->super() == vmClasses::Enum_klass()));
873 }
874
875 bool InstanceKlass::should_be_initialized() const {
876 return !is_initialized();
877 }
878
879 // Static size helper
880 int InstanceKlass::size(int vtable_length,
881 int itable_length,
882 int nonstatic_oop_map_size,
883 bool is_interface,
884 bool is_inline_type) {
885 return align_metadata_size(header_size() +
886 vtable_length +
887 itable_length +
888 nonstatic_oop_map_size +
889 (is_interface ? (int)sizeof(Klass*) / wordSize : 0) +
890 (is_inline_type ? (int)sizeof(InlineKlass::Members) / wordSize : 0));
891 }
892
893 int InstanceKlass::size() const {
894 return size(vtable_length(),
895 itable_length(),
896 nonstatic_oop_map_size(),
897 is_interface(),
898 is_inline_klass());
899 }
900
901 klassItable InstanceKlass::itable() const {
902 return klassItable(const_cast<InstanceKlass*>(this));
903 }
904
905 // JVMTI spec thinks there are signers and protection domain in the
906 // instanceKlass. These accessors pretend these fields are there.
907 // The hprof specification also thinks these fields are in InstanceKlass.
908 oop InstanceKlass::protection_domain() const {
909 // return the protection_domain from the mirror
910 return java_lang_Class::protection_domain(java_mirror());
911 }
912
913 objArrayOop InstanceKlass::signers() const {
914 // return the signers from the mirror
915 return java_lang_Class::signers(java_mirror());
916 }
917
918 oop InstanceKlass::init_lock() const {
919 // return the init lock from the mirror
920 oop lock = java_lang_Class::init_lock(java_mirror());
1056 #ifdef ASSERT
1057 {
1058 Handle h_init_lock(THREAD, init_lock());
1059 ObjectLocker ol(h_init_lock, THREAD);
1060 assert(!is_initialized(), "sanity");
1061 assert(!is_being_initialized(), "sanity");
1062 assert(!is_in_error_state(), "sanity");
1063 }
1064 #endif
1065
1066 set_init_thread(THREAD);
1067 set_initialization_state_and_notify(fully_initialized, CHECK);
1068 }
1069 #endif
1070
1071 bool InstanceKlass::verify_code(TRAPS) {
1072 // 1) Verify the bytecodes
1073 return Verifier::verify(this, should_verify_class(), THREAD);
1074 }
1075
1076 static void load_classes_from_loadable_descriptors_attribute(InstanceKlass *ik, TRAPS) {
1077 if (ik->loadable_descriptors() != Universe::the_empty_short_array() && PreloadClasses) {
1078 ResourceMark rm(THREAD);
1079 HandleMark hm(THREAD);
1080 for (int i = 0; i < ik->loadable_descriptors()->length(); i++) {
1081 Symbol* sig = ik->constants()->symbol_at(ik->loadable_descriptors()->at(i));
1082 if (!Signature::has_envelope(sig)) continue;
1083 TempNewSymbol class_name = Signature::strip_envelope(sig);
1084 if (class_name == ik->name()) continue;
1085 log_info(class, preload)("Preloading of class %s during linking of class %s "
1086 "because of the class is listed in the LoadableDescriptors attribute",
1087 sig->as_C_string(), ik->name()->as_C_string());
1088 oop loader = ik->class_loader();
1089 Klass* klass = SystemDictionary::resolve_or_null(class_name,
1090 Handle(THREAD, loader), THREAD);
1091 if (HAS_PENDING_EXCEPTION) {
1092 CLEAR_PENDING_EXCEPTION;
1093 }
1094 if (klass != nullptr) {
1095 log_info(class, preload)("Preloading of class %s during linking of class %s "
1096 "(cause: LoadableDescriptors attribute) succeeded",
1097 class_name->as_C_string(), ik->name()->as_C_string());
1098 if (!klass->is_inline_klass()) {
1099 // Non value class are allowed by the current spec, but it could be an indication
1100 // of an issue so let's log a warning
1101 log_info(class, preload)("Preloading of class %s during linking of class %s "
1102 "(cause: LoadableDescriptors attribute) but loaded class is not a value class",
1103 class_name->as_C_string(), ik->name()->as_C_string());
1104 }
1105 } else {
1106 log_info(class, preload)("Preloading of class %s during linking of class %s "
1107 "(cause: LoadableDescriptors attribute) failed",
1108 class_name->as_C_string(), ik->name()->as_C_string());
1109 }
1110 }
1111 }
1112 }
1113
1114 void InstanceKlass::link_class(TRAPS) {
1115 assert(is_loaded(), "must be loaded");
1116 if (!is_linked()) {
1117 link_class_impl(CHECK);
1118 }
1119 }
1120
1121 // Called to verify that a class can link during initialization, without
1122 // throwing a VerifyError.
1123 bool InstanceKlass::link_class_or_fail(TRAPS) {
1124 assert(is_loaded(), "must be loaded");
1125 if (!is_linked()) {
1126 link_class_impl(CHECK_false);
1127 }
1128 return is_linked();
1129 }
1130
1131 bool InstanceKlass::link_class_impl(TRAPS) {
1132 if (CDSConfig::is_dumping_static_archive() && SystemDictionaryShared::has_class_failed_verification(this)) {
1133 // This is for CDS static dump only -- we use the in_error_state to indicate that
1164 THREAD_AND_LOCATION,
1165 vmSymbols::java_lang_IncompatibleClassChangeError(),
1166 "class %s has interface %s as super class",
1167 external_name(),
1168 super_klass->external_name()
1169 );
1170 return false;
1171 }
1172
1173 super_klass->link_class_impl(CHECK_false);
1174 }
1175
1176 // link all interfaces implemented by this class before linking this class
1177 Array<InstanceKlass*>* interfaces = local_interfaces();
1178 int num_interfaces = interfaces->length();
1179 for (int index = 0; index < num_interfaces; index++) {
1180 InstanceKlass* interk = interfaces->at(index);
1181 interk->link_class_impl(CHECK_false);
1182 }
1183
1184 if (Arguments::is_valhalla_enabled()) {
1185 // Aggressively preloading all classes from the LoadableDescriptors attribute
1186 // so inline classes can be scalarized in the calling conventions computed below
1187 load_classes_from_loadable_descriptors_attribute(this, THREAD);
1188 assert(!HAS_PENDING_EXCEPTION, "Shouldn't have pending exceptions from call above");
1189 }
1190
1191 // in case the class is linked in the process of linking its superclasses
1192 if (is_linked()) {
1193 return true;
1194 }
1195
1196 // trace only the link time for this klass that includes
1197 // the verification time
1198 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
1199 ClassLoader::perf_class_link_selftime(),
1200 ClassLoader::perf_classes_linked(),
1201 jt->get_thread_stat()->perf_recursion_counts_addr(),
1202 jt->get_thread_stat()->perf_timers_addr(),
1203 PerfClassTraceTime::CLASS_LINK);
1204
1205 // verification & rewriting
1206 {
1207 HandleMark hm(THREAD);
1208 Handle h_init_lock(THREAD, init_lock());
1209 ObjectLocker ol(h_init_lock, CHECK_PREEMPTABLE_false);
1210 // Don't allow preemption if we link/initialize classes below,
1500 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1501 ss.as_string(), cause);
1502 }
1503 } else {
1504
1505 // Step 6
1506 set_init_state(being_initialized);
1507 set_init_thread(jt);
1508 if (debug_logging_enabled) {
1509 ResourceMark rm(jt);
1510 log_debug(class, init)("Thread \"%s\" is initializing %s",
1511 jt->name(), external_name());
1512 }
1513 }
1514 }
1515
1516 // Block preemption once we are the initializer thread. Unmounting now
1517 // would complicate the reentrant case (identity is platform thread).
1518 NoPreemptMark npm(THREAD);
1519
1520 // Pre-allocating an all-zero value to be used to reset nullable flat storages
1521 if (is_inline_klass()) {
1522 InlineKlass* vk = InlineKlass::cast(this);
1523 if (vk->supports_nullable_layouts()) {
1524 oop val = vk->allocate_instance(THREAD);
1525 if (HAS_PENDING_EXCEPTION) {
1526 Handle e(THREAD, PENDING_EXCEPTION);
1527 CLEAR_PENDING_EXCEPTION;
1528 {
1529 EXCEPTION_MARK;
1530 add_initialization_error(THREAD, e);
1531 // Locks object, set state, and notify all waiting threads
1532 set_initialization_state_and_notify(initialization_error, THREAD);
1533 CLEAR_PENDING_EXCEPTION;
1534 }
1535 THROW_OOP(e());
1536 }
1537 vk->set_null_reset_value(val);
1538 }
1539 }
1540
1541 // Step 7
1542 // Next, if C is a class rather than an interface, initialize it's super class and super
1543 // interfaces.
1544 if (!is_interface()) {
1545 Klass* super_klass = super();
1546 if (super_klass != nullptr && super_klass->should_be_initialized()) {
1547 super_klass->initialize(THREAD);
1548 }
1549 // If C implements any interface that declares a non-static, concrete method,
1550 // the initialization of C triggers initialization of its super interfaces.
1551 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1552 // having a superinterface that declares, non-static, concrete methods
1553 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1554 initialize_super_interfaces(THREAD);
1555 }
1556
1557 // If any exceptions, complete abruptly, throwing the same exception as above.
1558 if (HAS_PENDING_EXCEPTION) {
1559 Handle e(THREAD, PENDING_EXCEPTION);
1560 CLEAR_PENDING_EXCEPTION;
1574 // Step 8
1575 {
1576 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1577 if (class_initializer() != nullptr) {
1578 // Timer includes any side effects of class initialization (resolution,
1579 // etc), but not recursive entry into call_class_initializer().
1580 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1581 ClassLoader::perf_class_init_selftime(),
1582 ClassLoader::perf_classes_inited(),
1583 jt->get_thread_stat()->perf_recursion_counts_addr(),
1584 jt->get_thread_stat()->perf_timers_addr(),
1585 PerfClassTraceTime::CLASS_CLINIT);
1586 call_class_initializer(THREAD);
1587 } else {
1588 // The elapsed time is so small it's not worth counting.
1589 if (UsePerfData) {
1590 ClassLoader::perf_classes_inited()->inc();
1591 }
1592 call_class_initializer(THREAD);
1593 }
1594
1595 if (has_strict_static_fields() && !HAS_PENDING_EXCEPTION) {
1596 // Step 9 also verifies that strict static fields have been initialized.
1597 // Status bits were set in ClassFileParser::post_process_parsed_stream.
1598 // After <clinit>, bits must all be clear, or else we must throw an error.
1599 // This is an extremely fast check, so we won't bother with a timer.
1600 assert(fields_status() != nullptr, "");
1601 Symbol* bad_strict_static = nullptr;
1602 for (int index = 0; index < fields_status()->length(); index++) {
1603 // Very fast loop over single byte array looking for a set bit.
1604 if (fields_status()->adr_at(index)->is_strict_static_unset()) {
1605 // This strict static field has not been set by the class initializer.
1606 // Note that in the common no-error case, we read no field metadata.
1607 // We only unpack it when we need to report an error.
1608 FieldInfo fi = field(index);
1609 bad_strict_static = fi.name(constants());
1610 if (debug_logging_enabled) {
1611 ResourceMark rm(jt);
1612 const char* msg = format_strict_static_message(bad_strict_static);
1613 log_debug(class, init)("%s", msg);
1614 } else {
1615 // If we are not logging, do not bother to look for a second offense.
1616 break;
1617 }
1618 }
1619 }
1620 if (bad_strict_static != nullptr) {
1621 throw_strict_static_exception(bad_strict_static, "is unset after initialization of", THREAD);
1622 }
1623 }
1624 }
1625
1626 // Step 9
1627 if (!HAS_PENDING_EXCEPTION) {
1628 set_initialization_state_and_notify(fully_initialized, CHECK);
1629 DEBUG_ONLY(vtable().verify(tty, true);)
1630 CompilationPolicy::replay_training_at_init(this, THREAD);
1631 }
1632 else {
1633 // Step 10 and 11
1634 Handle e(THREAD, PENDING_EXCEPTION);
1635 CLEAR_PENDING_EXCEPTION;
1636 // JVMTI has already reported the pending exception
1637 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1638 JvmtiExport::clear_detected_exception(jt);
1639 {
1640 EXCEPTION_MARK;
1641 add_initialization_error(THREAD, e);
1642 set_initialization_state_and_notify(initialization_error, THREAD);
1643 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1657 }
1658 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1659 }
1660
1661
1662 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1663 Handle h_init_lock(THREAD, init_lock());
1664 if (h_init_lock() != nullptr) {
1665 ObjectLocker ol(h_init_lock, THREAD);
1666 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1667 set_init_state(state);
1668 fence_and_clear_init_lock();
1669 ol.notify_all(CHECK);
1670 } else {
1671 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1672 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1673 set_init_state(state);
1674 }
1675 }
1676
1677 void InstanceKlass::notify_strict_static_access(int field_index, bool is_writing, TRAPS) {
1678 guarantee(field_index >= 0 && field_index < fields_status()->length(), "valid field index");
1679 DEBUG_ONLY(FieldInfo debugfi = field(field_index));
1680 assert(debugfi.access_flags().is_strict(), "");
1681 assert(debugfi.access_flags().is_static(), "");
1682 FieldStatus& fs = *fields_status()->adr_at(field_index);
1683 LogTarget(Trace, class, init) lt;
1684 if (lt.is_enabled()) {
1685 ResourceMark rm(THREAD);
1686 LogStream ls(lt);
1687 FieldInfo fi = field(field_index);
1688 ls.print("notify %s %s %s%s ",
1689 external_name(), is_writing? "Write" : "Read",
1690 fs.is_strict_static_unset() ? "Unset" : "(set)",
1691 fs.is_strict_static_unread() ? "+Unread" : "");
1692 fi.print(&ls, constants());
1693 }
1694 if (fs.is_strict_static_unset()) {
1695 assert(fs.is_strict_static_unread(), "ClassFileParser resp.");
1696 // If it is not set, there are only two reasonable things we can do here:
1697 // - mark it set if this is putstatic
1698 // - throw an error (Read-Before-Write) if this is getstatic
1699
1700 // The unset state is (or should be) transient, and observable only in one
1701 // thread during the execution of <clinit>. Something is wrong here as this
1702 // should not be possible
1703 guarantee(is_reentrant_initialization(THREAD), "unscoped access to strict static");
1704 if (is_writing) {
1705 // clear the "unset" bit, since the field is actually going to be written
1706 fs.update_strict_static_unset(false);
1707 } else {
1708 // throw an IllegalStateException, since we are reading before writing
1709 // see also InstanceKlass::initialize_impl, Step 8 (at end)
1710 Symbol* bad_strict_static = field(field_index).name(constants());
1711 throw_strict_static_exception(bad_strict_static, "is unset before first read in", CHECK);
1712 }
1713 } else {
1714 // Ensure no write after read for final strict statics
1715 FieldInfo fi = field(field_index);
1716 bool is_final = fi.access_flags().is_final();
1717 if (is_final) {
1718 // no final write after read, so observing a constant freezes it, as if <clinit> ended early
1719 // (maybe we could trust the constant a little earlier, before <clinit> ends)
1720 if (is_writing && !fs.is_strict_static_unread()) {
1721 Symbol* bad_strict_static = fi.name(constants());
1722 throw_strict_static_exception(bad_strict_static, "is set after read (as final) in", CHECK);
1723 } else if (!is_writing && fs.is_strict_static_unread()) {
1724 fs.update_strict_static_unread(false);
1725 }
1726 }
1727 }
1728 }
1729
1730 void InstanceKlass::throw_strict_static_exception(Symbol* field_name, const char* when, TRAPS) {
1731 ResourceMark rm(THREAD);
1732 const char* msg = format_strict_static_message(field_name, when);
1733 THROW_MSG(vmSymbols::java_lang_IllegalStateException(), msg);
1734 }
1735
1736 const char* InstanceKlass::format_strict_static_message(Symbol* field_name, const char* when) {
1737 stringStream ss;
1738 ss.print("Strict static \"%s\" %s %s",
1739 field_name->as_C_string(),
1740 when == nullptr ? "is unset in" : when,
1741 external_name());
1742 return ss.as_string();
1743 }
1744
1745 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1746 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1747 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1748 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1749
1750 DeoptimizationScope deopt_scope;
1751 {
1752 MutexLocker ml(current, Compile_lock);
1753
1754 set_init_state(InstanceKlass::loaded);
1755 // make sure init_state store is already done.
1756 // The compiler reads the hierarchy outside of the Compile_lock.
1757 // Access ordering is used to add to hierarchy.
1758
1759 // Link into hierarchy.
1760 append_to_sibling_list(); // add to superklass/sibling list
1761 process_interfaces(); // handle all "implements" declarations
1762
1763 // Now mark all code that depended on old class hierarchy.
1764 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1975 : vmSymbols::java_lang_IllegalAccessException(), external_name());
1976 }
1977 }
1978
1979 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
1980 // Need load-acquire for lock-free read
1981 if (array_klasses_acquire() == nullptr) {
1982
1983 // Recursively lock array allocation
1984 RecursiveLocker rl(MultiArray_lock, THREAD);
1985
1986 // Check if another thread created the array klass while we were waiting for the lock.
1987 if (array_klasses() == nullptr) {
1988 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
1989 // use 'release' to pair with lock-free load
1990 release_set_array_klasses(k);
1991 }
1992 }
1993
1994 // array_klasses() will always be set at this point
1995 ArrayKlass* ak = array_klasses();
1996 assert(ak != nullptr, "should be set");
1997 return ak->array_klass(n, THREAD);
1998 }
1999
2000 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
2001 // Need load-acquire for lock-free read
2002 ArrayKlass* ak = array_klasses_acquire();
2003 if (ak == nullptr) {
2004 return nullptr;
2005 } else {
2006 return ak->array_klass_or_null(n);
2007 }
2008 }
2009
2010 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
2011 return array_klass(1, THREAD);
2012 }
2013
2014 ArrayKlass* InstanceKlass::array_klass_or_null() {
2015 return array_klass_or_null(1);
2016 }
2017
2018 Method* InstanceKlass::class_initializer() const {
2019 Method* clinit = find_method(
2020 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
2021 if (clinit != nullptr && clinit->is_class_initializer()) {
2022 return clinit;
2023 }
2024 return nullptr;
2025 }
2026
2027 void InstanceKlass::call_class_initializer(TRAPS) {
2028 if (ReplayCompiles &&
2029 (ReplaySuppressInitializers == 1 ||
2030 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
2031 // Hide the existence of the initializer for the purpose of replaying the compile
2032 return;
2033 }
2034
2035 #if INCLUDE_CDS
2036 // This is needed to ensure the consistency of the archived heap objects.
2037 if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
2038 AOTClassInitializer::call_runtime_setup(THREAD, this);
2039 return;
2040 } else if (has_archived_enum_objs()) {
2041 assert(in_aot_cache(), "must be");
2110
2111 void InstanceKlass::mask_for(const methodHandle& method, int bci,
2112 InterpreterOopMap* entry_for) {
2113 // Lazily create the _oop_map_cache at first request.
2114 // Load_acquire is needed to safely get instance published with CAS by another thread.
2115 OopMapCache* oop_map_cache = AtomicAccess::load_acquire(&_oop_map_cache);
2116 if (oop_map_cache == nullptr) {
2117 // Try to install new instance atomically.
2118 oop_map_cache = new OopMapCache();
2119 OopMapCache* other = AtomicAccess::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
2120 if (other != nullptr) {
2121 // Someone else managed to install before us, ditch local copy and use the existing one.
2122 delete oop_map_cache;
2123 oop_map_cache = other;
2124 }
2125 }
2126 // _oop_map_cache is constant after init; lookup below does its own locking.
2127 oop_map_cache->lookup(method, bci, entry_for);
2128 }
2129
2130
2131 FieldInfo InstanceKlass::field(int index) const {
2132 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2133 if (fs.index() == index) {
2134 return fs.to_FieldInfo();
2135 }
2136 }
2137 fatal("Field not found");
2138 return FieldInfo();
2139 }
2140
2141 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
2142 JavaFieldStream fs(this);
2143 if (fs.lookup(name, sig)) {
2144 assert(fs.name() == name, "name must match");
2145 assert(fs.signature() == sig, "signature must match");
2146 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2147 return true;
2148 }
2149 return false;
2190
2191 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
2192 // search order according to newest JVM spec (5.4.3.2, p.167).
2193 // 1) search for field in current klass
2194 if (find_local_field(name, sig, fd)) {
2195 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
2196 }
2197 // 2) search for field recursively in direct superinterfaces
2198 if (is_static) {
2199 Klass* intf = find_interface_field(name, sig, fd);
2200 if (intf != nullptr) return intf;
2201 }
2202 // 3) apply field lookup recursively if superclass exists
2203 { InstanceKlass* supr = super();
2204 if (supr != nullptr) return supr->find_field(name, sig, is_static, fd);
2205 }
2206 // 4) otherwise field lookup fails
2207 return nullptr;
2208 }
2209
2210 bool InstanceKlass::contains_field_offset(int offset) {
2211 if (this->is_inline_klass()) {
2212 InlineKlass* vk = InlineKlass::cast(this);
2213 return offset >= vk->payload_offset() && offset < (vk->payload_offset() + vk->payload_size_in_bytes());
2214 } else {
2215 fieldDescriptor fd;
2216 return find_field_from_offset(offset, false, &fd);
2217 }
2218 }
2219
2220 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2221 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2222 if (fs.offset() == offset) {
2223 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2224 if (fd->is_static() == is_static) return true;
2225 }
2226 }
2227 return false;
2228 }
2229
2230
2231 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2232 const InstanceKlass* klass = this;
2233 while (klass != nullptr) {
2234 if (klass->find_local_field_from_offset(offset, is_static, fd)) {
2235 return true;
2236 }
2237 klass = klass->super();
2238 }
2239 return false;
2240 }
2241
2242 bool InstanceKlass::find_local_flat_field_containing_offset(int offset, fieldDescriptor* fd) const {
2243 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2244 if (!fs.is_flat()) {
2245 continue;
2246 }
2247
2248 if (fs.offset() > offset) {
2249 continue;
2250 }
2251
2252 const int offset_in_flat_field = offset - fs.offset();
2253 const InlineLayoutInfo layout_info = inline_layout_info(fs.index());
2254 const int field_size = layout_info.klass()->layout_size_in_bytes(layout_info.kind());
2255
2256 assert(LayoutKindHelper::is_flat(layout_info.kind()), "Must be flat");
2257
2258 if (offset_in_flat_field < field_size) {
2259 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2260 assert(!fd->is_static(), "Static fields are not flattened");
2261
2262 return true;
2263 }
2264 }
2265
2266 return false;
2267 }
2268
2269 bool InstanceKlass::find_flat_field_containing_offset(int offset, fieldDescriptor* fd) const {
2270 const InstanceKlass* klass = this;
2271 while (klass != nullptr) {
2272 if (klass->find_local_flat_field_containing_offset(offset, fd)) {
2273 return true;
2274 }
2275
2276 klass = klass->super();
2277 }
2278
2279 return false;
2280 }
2281
2282 void InstanceKlass::methods_do(void f(Method* method)) {
2283 // Methods aren't stable until they are loaded. This can be read outside
2284 // a lock through the ClassLoaderData for profiling
2285 // Redefined scratch classes are on the list and need to be cleaned
2286 if (!is_loaded() && !is_scratch_class()) {
2287 return;
2288 }
2289
2290 int len = methods()->length();
2291 for (int index = 0; index < len; index++) {
2292 Method* m = methods()->at(index);
2293 assert(m->is_method(), "must be method");
2294 f(m);
2295 }
2296 }
2297
2298
2299 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
2300 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2301 if (fs.access_flags().is_static()) {
2302 fieldDescriptor& fd = fs.field_descriptor();
2303 cl->do_field(&fd);
2304 }
2305 }
2306 }
2307
2308
2309 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
2310 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2311 if (fs.access_flags().is_static()) {
2312 fieldDescriptor& fd = fs.field_descriptor();
2313 f(&fd, mirror, CHECK);
2314 }
2315 }
2316 }
2317
2318 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
2319 InstanceKlass* super = this->super();
2320 if (super != nullptr) {
2321 super->do_nonstatic_fields(cl);
2322 }
2323 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2324 fieldDescriptor& fd = fs.field_descriptor();
2325 if (!fd.is_static()) {
2326 cl->do_field(&fd);
2327 }
2328 }
2329 }
2330
2621 }
2622
2623 // uncached_lookup_method searches both the local class methods array and all
2624 // superclasses methods arrays, skipping any overpass methods in superclasses,
2625 // and possibly skipping private methods.
2626 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2627 const Symbol* signature,
2628 OverpassLookupMode overpass_mode,
2629 PrivateLookupMode private_mode) const {
2630 OverpassLookupMode overpass_local_mode = overpass_mode;
2631 const InstanceKlass* klass = this;
2632 while (klass != nullptr) {
2633 Method* const method = klass->find_method_impl(name,
2634 signature,
2635 overpass_local_mode,
2636 StaticLookupMode::find,
2637 private_mode);
2638 if (method != nullptr) {
2639 return method;
2640 }
2641 if (name == vmSymbols::object_initializer_name()) {
2642 break; // <init> is never inherited
2643 }
2644 klass = klass->super();
2645 overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses
2646 }
2647 return nullptr;
2648 }
2649
2650 #ifdef ASSERT
2651 // search through class hierarchy and return true if this class or
2652 // one of the superclasses was redefined
2653 bool InstanceKlass::has_redefined_this_or_super() const {
2654 const InstanceKlass* klass = this;
2655 while (klass != nullptr) {
2656 if (klass->has_been_redefined()) {
2657 return true;
2658 }
2659 klass = klass->super();
2660 }
2661 return false;
2662 }
2663 #endif
3036 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
3037
3038 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
3039 / itableOffsetEntry::size();
3040
3041 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
3042 if (ioe->interface_klass() != nullptr) {
3043 it->push(ioe->interface_klass_addr());
3044 itableMethodEntry* ime = ioe->first_method_entry(this);
3045 int n = klassItable::method_count_for_interface(ioe->interface_klass());
3046 for (int index = 0; index < n; index ++) {
3047 it->push(ime[index].method_addr());
3048 }
3049 }
3050 }
3051 }
3052
3053 it->push(&_nest_host);
3054 it->push(&_nest_members);
3055 it->push(&_permitted_subclasses);
3056 it->push(&_loadable_descriptors);
3057 it->push(&_acmp_maps_array, MetaspaceClosure::_writable);
3058 it->push(&_record_components);
3059 it->push(&_inline_layout_info_array, MetaspaceClosure::_writable);
3060
3061 if (CDSConfig::is_dumping_full_module_graph() && !defined_by_other_loaders()) {
3062 it->push(&_package_entry);
3063 }
3064 }
3065
3066 #if INCLUDE_CDS
3067 void InstanceKlass::remove_unshareable_info() {
3068
3069 if (is_linked()) {
3070 assert(can_be_verified_at_dumptime(), "must be");
3071 // Remember this so we can avoid walking the hierarchy at runtime.
3072 set_verified_at_dump_time();
3073 }
3074
3075 _misc_flags.set_has_init_deps_processed(false);
3076
3077 Klass::remove_unshareable_info();
3078
3079 if (SystemDictionaryShared::has_class_failed_verification(this)) {
3091
3092 { // Otherwise this needs to take out the Compile_lock.
3093 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
3094 init_implementor();
3095 }
3096
3097 // Call remove_unshareable_info() on other objects that belong to this class, except
3098 // for constants()->remove_unshareable_info(), which is called in a separate pass in
3099 // ArchiveBuilder::make_klasses_shareable(),
3100
3101 for (int i = 0; i < methods()->length(); i++) {
3102 Method* m = methods()->at(i);
3103 m->remove_unshareable_info();
3104 }
3105
3106 // do array classes also.
3107 if (array_klasses() != nullptr) {
3108 array_klasses()->remove_unshareable_info();
3109 }
3110
3111 // These are not allocated from metaspace. They are safe to set to nullptr.
3112 _source_debug_extension = nullptr;
3113 _dep_context = nullptr;
3114 _osr_nmethods_head = nullptr;
3115 #if INCLUDE_JVMTI
3116 _breakpoints = nullptr;
3117 _previous_versions = nullptr;
3118 _cached_class_file = nullptr;
3119 _jvmti_cached_class_field_map = nullptr;
3120 #endif
3121
3122 _init_thread = nullptr;
3123 _methods_jmethod_ids = nullptr;
3124 _jni_ids = nullptr;
3125 _oop_map_cache = nullptr;
3126 if (CDSConfig::is_dumping_method_handles() && HeapShared::is_lambda_proxy_klass(this)) {
3127 // keep _nest_host
3128 } else {
3129 // clear _nest_host to ensure re-load at runtime
3130 _nest_host = nullptr;
3131 }
3167 void InstanceKlass::compute_has_loops_flag_for_methods() {
3168 Array<Method*>* methods = this->methods();
3169 for (int index = 0; index < methods->length(); ++index) {
3170 Method* m = methods->at(index);
3171 if (!m->is_overpass()) { // work around JDK-8305771
3172 m->compute_has_loops_flag();
3173 }
3174 }
3175 }
3176
3177 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
3178 PackageEntry* pkg_entry, TRAPS) {
3179 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
3180 // before the InstanceKlass is added to the SystemDictionary. Make
3181 // sure the current state is <loaded.
3182 assert(!is_loaded(), "invalid init state");
3183 assert(!shared_loading_failed(), "Must not try to load failed class again");
3184 set_package(loader_data, pkg_entry, CHECK);
3185 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
3186
3187 if (is_inline_klass()) {
3188 InlineKlass::cast(this)->initialize_calling_convention(CHECK);
3189 }
3190
3191 Array<Method*>* methods = this->methods();
3192 int num_methods = methods->length();
3193 for (int index = 0; index < num_methods; ++index) {
3194 methods->at(index)->restore_unshareable_info(CHECK);
3195 }
3196 #if INCLUDE_JVMTI
3197 if (JvmtiExport::has_redefined_a_class()) {
3198 // Reinitialize vtable because RedefineClasses may have changed some
3199 // entries in this vtable for super classes so the CDS vtable might
3200 // point to old or obsolete entries. RedefineClasses doesn't fix up
3201 // vtables in the shared system dictionary, only the main one.
3202 // It also redefines the itable too so fix that too.
3203 // First fix any default methods that point to a super class that may
3204 // have been redefined.
3205 bool trace_name_printed = false;
3206 adjust_default_methods(&trace_name_printed);
3207 if (verified_at_dump_time()) {
3208 // Initialize vtable and itable for classes which can be verified at dump time.
3209 // Unlinked classes such as old classes with major version < 50 cannot be verified
3210 // at dump time.
3211 vtable().initialize_vtable();
3212 itable().initialize_itable();
3213 }
3214 }
3215 #endif // INCLUDE_JVMTI
3216
3217 // restore constant pool resolved references
3218 constants()->restore_unshareable_info(CHECK);
3219
3220 // Restore acmp_maps java array from the version stored in metadata.
3221 // if it cannot be found in the archive
3222 if (Arguments::is_valhalla_enabled() && has_acmp_maps_offset() && java_mirror()->obj_field(_acmp_maps_offset) == nullptr) {
3223 int acmp_maps_size = _acmp_maps_array->length();
3224 typeArrayOop map = oopFactory::new_intArray(acmp_maps_size, CHECK);
3225 typeArrayHandle map_h(THREAD, map);
3226 for (int i = 0; i < acmp_maps_size; i++) {
3227 map_h->int_at_put(i, _acmp_maps_array->at(i));
3228 }
3229 java_mirror()->obj_field_put(_acmp_maps_offset, map_h());
3230 }
3231
3232 if (array_klasses() != nullptr) {
3233 // To get a consistent list of classes we need MultiArray_lock to ensure
3234 // array classes aren't observed while they are being restored.
3235 RecursiveLocker rl(MultiArray_lock, THREAD);
3236 assert(this == ObjArrayKlass::cast(array_klasses())->bottom_klass(), "sanity");
3237 // Array classes have null protection domain.
3238 // --> see ArrayKlass::complete_create_array_klass()
3239 if (class_loader_data() == nullptr) {
3240 ResourceMark rm(THREAD);
3241 log_debug(cds)(" loader_data %s ", loader_data == nullptr ? "nullptr" : "non null");
3242 log_debug(cds)(" this %s array_klasses %s ", this->name()->as_C_string(), array_klasses()->name()->as_C_string());
3243 }
3244 assert(!array_klasses()->is_refined_objArray_klass(), "must be non-refined objarrayklass");
3245 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
3246 }
3247
3248 // Initialize @ValueBased class annotation if not already set in the archived klass.
3249 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
3250 set_is_value_based();
3251 }
3252
3253 DEBUG_ONLY(FieldInfoStream::validate_search_table(_constants, _fieldinfo_stream, _fieldinfo_search_table));
3254 }
3255
3256 bool InstanceKlass::can_be_verified_at_dumptime() const {
3257 if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(this)) {
3258 // This is a class that was dumped into the base archive, so we know
3259 // it was verified at dump time.
3260 return true;
3261 }
3262
3263 if (CDSConfig::is_preserving_verification_constraints()) {
3264 return true;
3380 constants()->release_C_heap_structures();
3381 }
3382 }
3383
3384 // The constant pool is on stack if any of the methods are executing or
3385 // referenced by handles.
3386 bool InstanceKlass::on_stack() const {
3387 return _constants->on_stack();
3388 }
3389
3390 Symbol* InstanceKlass::source_file_name() const { return _constants->source_file_name(); }
3391 u2 InstanceKlass::source_file_name_index() const { return _constants->source_file_name_index(); }
3392 void InstanceKlass::set_source_file_name_index(u2 sourcefile_index) { _constants->set_source_file_name_index(sourcefile_index); }
3393
3394 // minor and major version numbers of class file
3395 u2 InstanceKlass::minor_version() const { return _constants->minor_version(); }
3396 void InstanceKlass::set_minor_version(u2 minor_version) { _constants->set_minor_version(minor_version); }
3397 u2 InstanceKlass::major_version() const { return _constants->major_version(); }
3398 void InstanceKlass::set_major_version(u2 major_version) { _constants->set_major_version(major_version); }
3399
3400 bool InstanceKlass::supports_inline_types() const {
3401 return major_version() >= Verifier::VALUE_TYPES_MAJOR_VERSION && minor_version() == Verifier::JAVA_PREVIEW_MINOR_VERSION;
3402 }
3403
3404 const InstanceKlass* InstanceKlass::get_klass_version(int version) const {
3405 for (const InstanceKlass* ik = this; ik != nullptr; ik = ik->previous_versions()) {
3406 if (ik->constants()->version() == version) {
3407 return ik;
3408 }
3409 }
3410 return nullptr;
3411 }
3412
3413 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
3414 if (array == nullptr) {
3415 _source_debug_extension = nullptr;
3416 } else {
3417 // Adding one to the attribute length in order to store a null terminator
3418 // character could cause an overflow because the attribute length is
3419 // already coded with an u4 in the classfile, but in practice, it's
3420 // unlikely to happen.
3421 assert((length+1) > length, "Overflow checking");
3422 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
3423 for (int i = 0; i < length; i++) {
3424 sde[i] = array[i];
3425 }
3426 sde[length] = '\0';
3427 _source_debug_extension = sde;
3428 }
3429 }
3430
3431 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); }
3432 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); }
3433 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); }
3434
3435 const char* InstanceKlass::signature_name() const {
3436 return signature_name_of_carrier(JVM_SIGNATURE_CLASS);
3437 }
3438
3439 const char* InstanceKlass::signature_name_of_carrier(char c) const {
3440 // Get the internal name as a c string
3441 const char* src = (const char*) (name()->as_C_string());
3442 const int src_length = (int)strlen(src);
3443
3444 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
3445
3446 // Add L or Q as type indicator
3447 int dest_index = 0;
3448 dest[dest_index++] = c;
3449
3450 // Add the actual class name
3451 for (int src_index = 0; src_index < src_length; ) {
3452 dest[dest_index++] = src[src_index++];
3453 }
3454
3455 if (is_hidden()) { // Replace the last '+' with a '.'.
3456 for (int index = (int)src_length; index > 0; index--) {
3457 if (dest[index] == '+') {
3458 dest[index] = JVM_SIGNATURE_DOT;
3459 break;
3460 }
3461 }
3462 }
3463
3464 // Add the semicolon and the null
3465 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3466 dest[dest_index] = '\0';
3467 return dest;
3468 }
3709 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3710 constantPoolHandle i_cp(THREAD, constants());
3711 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3712 int ioff = iter.inner_class_info_index();
3713 if (ioff != 0) {
3714 // Check to see if the name matches the class we're looking for
3715 // before attempting to find the class.
3716 if (i_cp->klass_name_at_matches(this, ioff)) {
3717 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3718 if (this == inner_klass) {
3719 *ooff = iter.outer_class_info_index();
3720 *noff = iter.inner_name_index();
3721 return true;
3722 }
3723 }
3724 }
3725 }
3726 return false;
3727 }
3728
3729 void InstanceKlass::check_can_be_annotated_with_NullRestricted(InstanceKlass* type, Symbol* container_klass_name, TRAPS) {
3730 assert(type->is_instance_klass(), "Sanity check");
3731 if (type->is_identity_class()) {
3732 ResourceMark rm(THREAD);
3733 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
3734 err_msg("Class %s expects class %s to be a value class, but it is an identity class",
3735 container_klass_name->as_C_string(),
3736 type->external_name()));
3737 }
3738
3739 if (type->is_abstract()) {
3740 ResourceMark rm(THREAD);
3741 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
3742 err_msg("Class %s expects class %s to be concrete value type, but it is an abstract class",
3743 container_klass_name->as_C_string(),
3744 type->external_name()));
3745 }
3746 }
3747
3748 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3749 InstanceKlass* outer_klass = nullptr;
3750 *inner_is_member = false;
3751 int ooff = 0, noff = 0;
3752 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3753 if (has_inner_classes_attr) {
3754 constantPoolHandle i_cp(THREAD, constants());
3755 if (ooff != 0) {
3756 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3757 if (!ok->is_instance_klass()) {
3758 // If the outer class is not an instance klass then it cannot have
3759 // declared any inner classes.
3760 ResourceMark rm(THREAD);
3761 // Names are all known to be < 64k so we know this formatted message is not excessively large.
3762 Exceptions::fthrow(
3763 THREAD_AND_LOCATION,
3764 vmSymbols::java_lang_IncompatibleClassChangeError(),
3765 "%s and %s disagree on InnerClasses attribute",
3766 ok->external_name(),
3767 external_name());
3794 u2 InstanceKlass::compute_modifier_flags() const {
3795 u2 access = access_flags().as_unsigned_short();
3796
3797 // But check if it happens to be member class.
3798 InnerClassesIterator iter(this);
3799 for (; !iter.done(); iter.next()) {
3800 int ioff = iter.inner_class_info_index();
3801 // Inner class attribute can be zero, skip it.
3802 // Strange but true: JVM spec. allows null inner class refs.
3803 if (ioff == 0) continue;
3804
3805 // only look at classes that are already loaded
3806 // since we are looking for the flags for our self.
3807 Symbol* inner_name = constants()->klass_name_at(ioff);
3808 if (name() == inner_name) {
3809 // This is really a member class.
3810 access = iter.inner_access_flags();
3811 break;
3812 }
3813 }
3814 if (!Arguments::is_valhalla_enabled()) {
3815 // Remember to strip ACC_SUPER bit without Valhalla
3816 access &= (~JVM_ACC_SUPER);
3817 }
3818 return access;
3819 }
3820
3821 jint InstanceKlass::jvmti_class_status() const {
3822 jint result = 0;
3823
3824 if (is_linked()) {
3825 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3826 }
3827
3828 if (is_initialized()) {
3829 assert(is_linked(), "Class status is not consistent");
3830 result |= JVMTI_CLASS_STATUS_INITIALIZED;
3831 }
3832 if (is_in_error_state()) {
3833 result |= JVMTI_CLASS_STATUS_ERROR;
3834 }
3835 return result;
3836 }
3837
3838 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
4052 }
4053 osr = osr->osr_link();
4054 }
4055
4056 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
4057 if (best != nullptr && best->comp_level() >= comp_level) {
4058 return best;
4059 }
4060 return nullptr;
4061 }
4062
4063 // -----------------------------------------------------------------------------------------------------
4064 // Printing
4065
4066 #define BULLET " - "
4067
4068 static const char* state_names[] = {
4069 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
4070 };
4071
4072 static void print_vtable(address self, intptr_t* start, int len, outputStream* st) {
4073 ResourceMark rm;
4074 int* forward_refs = NEW_RESOURCE_ARRAY(int, len);
4075 for (int i = 0; i < len; i++) forward_refs[i] = 0;
4076 for (int i = 0; i < len; i++) {
4077 intptr_t e = start[i];
4078 st->print("%d : " INTPTR_FORMAT, i, e);
4079 if (forward_refs[i] != 0) {
4080 int from = forward_refs[i];
4081 int off = (int) start[from];
4082 st->print(" (offset %d <= [%d])", off, from);
4083 }
4084 if (MetaspaceObj::is_valid((Metadata*)e)) {
4085 st->print(" ");
4086 ((Metadata*)e)->print_value_on(st);
4087 } else if (self != nullptr && e > 0 && e < 0x10000) {
4088 address location = self + e;
4089 int index = (int)((intptr_t*)location - start);
4090 st->print(" (offset %d => [%d])", (int)e, index);
4091 if (index >= 0 && index < len)
4092 forward_refs[index] = i;
4093 }
4094 st->cr();
4095 }
4096 }
4097
4098 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
4099 return print_vtable(nullptr, reinterpret_cast<intptr_t*>(start), len, st);
4100 }
4101
4102 const char* InstanceKlass::init_state_name() const {
4103 return state_names[init_state()];
4104 }
4105
4106 void InstanceKlass::print_on(outputStream* st) const {
4107 assert(is_klass(), "must be klass");
4108 Klass::print_on(st);
4109
4110 st->print(BULLET"instance size: %d", size_helper()); st->cr();
4111 st->print(BULLET"klass size: %d", size()); st->cr();
4112 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
4113 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
4114 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
4115 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
4116 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
4117 st->print(BULLET"sub: ");
4118 Klass* sub = subklass();
4119 int n;
4120 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
4121 if (n < MaxSubklassPrintSize) {
4122 sub->print_value_on(st);
4123 st->print(" ");
4124 }
4125 }
4126 if (n >= MaxSubklassPrintSize) st->print("(%zd more klasses...)", n - MaxSubklassPrintSize);
4127 st->cr();
4128
4129 if (is_interface()) {
4130 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
4131 if (nof_implementors() == 1) {
4132 st->print_cr(BULLET"implementor: ");
4133 st->print(" ");
4134 implementor()->print_value_on(st);
4135 st->cr();
4136 }
4137 }
4138
4139 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
4140 st->print(BULLET"methods: ");
4141 print_array_on(st, methods(), [](outputStream* ost, Method* method) {
4142 method->print_value_on(ost);
4143 });
4144 st->print(BULLET"method ordering: ");
4145 print_array_on(st, method_ordering(), [](outputStream* ost, int i) {
4146 ost->print("%d", i);
4147 });
4148 if (default_methods() != nullptr) {
4149 st->print(BULLET"default_methods: ");
4150 print_array_on(st, default_methods(), [](outputStream* ost, Method* method) {
4151 method->print_value_on(ost);
4152 });
4153 }
4154 print_on_maybe_null(st, BULLET"default vtable indices: ", default_vtable_indices());
4155 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
4156 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
4157
4158 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr();
4159
4160 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr();
4161 st->print(BULLET"secondary bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap); st->cr();
4162
4163 if (secondary_supers() != nullptr) {
4164 if (Verbose) {
4165 bool is_hashed = (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL);
4166 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length());
4167 for (int i = 0; i < _secondary_supers->length(); i++) {
4168 ResourceMark rm; // for external_name()
4169 Klass* secondary_super = _secondary_supers->at(i);
4170 st->print(BULLET"%2d:", i);
4171 if (is_hashed) {
4172 int home_slot = compute_home_slot(secondary_super, _secondary_supers_bitmap);
4192 print_on_maybe_null(st, BULLET"field type annotations: ", fields_type_annotations());
4193 {
4194 bool have_pv = false;
4195 // previous versions are linked together through the InstanceKlass
4196 for (InstanceKlass* pv_node = previous_versions();
4197 pv_node != nullptr;
4198 pv_node = pv_node->previous_versions()) {
4199 if (!have_pv)
4200 st->print(BULLET"previous version: ");
4201 have_pv = true;
4202 pv_node->constants()->print_value_on(st);
4203 }
4204 if (have_pv) st->cr();
4205 }
4206
4207 print_on_maybe_null(st, BULLET"generic signature: ", generic_signature());
4208 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
4209 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();
4210 print_on_maybe_null(st, BULLET"record components: ", record_components());
4211 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();
4212 st->print(BULLET"loadable descriptors: "); loadable_descriptors()->print_value_on(st); st->cr();
4213 if (java_mirror() != nullptr) {
4214 st->print(BULLET"java mirror: ");
4215 java_mirror()->print_value_on(st);
4216 st->cr();
4217 } else {
4218 st->print_cr(BULLET"java mirror: null");
4219 }
4220 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
4221 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);
4222 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
4223 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(nullptr, start_of_itable(), itable_length(), st);
4224
4225 InstanceKlass* ik = const_cast<InstanceKlass*>(this);
4226 // There is no oop so static and nonstatic printing can use the same printer.
4227 FieldPrinter field_printer(st);
4228 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
4229 ik->do_local_static_fields(&field_printer);
4230 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
4231 ik->print_nonstatic_fields(&field_printer);
4232
4233 st->print(BULLET"non-static oop maps (%d entries): ", nonstatic_oop_map_count());
4234 OopMapBlock* map = start_of_nonstatic_oop_maps();
4235 OopMapBlock* end_map = map + nonstatic_oop_map_count();
4236 while (map < end_map) {
4237 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
4238 map++;
4239 }
4240 st->cr();
4241
4242 if (fieldinfo_search_table() != nullptr) {
4243 st->print_cr(BULLET"---- field info search table:");
4244 FieldInfoStream::print_search_table(st, _constants, _fieldinfo_stream, _fieldinfo_search_table);
4245 }
4246 }
4247
4248 void InstanceKlass::print_value_on(outputStream* st) const {
4249 assert(is_klass(), "must be klass");
4250 if (Verbose || WizardMode) access_flags().print_on(st);
4251 name()->print_value_on(st);
4252 }
4253
4254 void FieldPrinter::do_field(fieldDescriptor* fd) {
4255 for (int i = 0; i < _indent; i++) _st->print(" ");
4256 _st->print(BULLET);
4257 // Handles the cases of static fields or instance fields but no oop is given.
4258 if (_obj == nullptr) {
4259 fd->print_on(_st, _base_offset);
4260 _st->cr();
4261 } else {
4262 fd->print_on_for(_st, _obj, _indent, _base_offset);
4263 if (!fd->field_flags().is_flat()) _st->cr();
4264 }
4265 }
4266
4267
4268 void InstanceKlass::oop_print_on(oop obj, outputStream* st, int indent, int base_offset) {
4269 Klass::oop_print_on(obj, st);
4270
4271 if (this == vmClasses::String_klass()) {
4272 typeArrayOop value = java_lang_String::value(obj);
4273 juint length = java_lang_String::length(obj);
4274 if (value != nullptr &&
4275 value->is_typeArray() &&
4276 length <= (juint) value->length()) {
4277 st->print(BULLET"string: ");
4278 java_lang_String::print(obj, st);
4279 st->cr();
4280 }
4281 }
4282
4283 st->print_cr(BULLET"---- fields (total size %zu words):", oop_size(obj));
4284 FieldPrinter print_field(st, obj, indent, base_offset);
4285 print_nonstatic_fields(&print_field);
4286
4287 if (this == vmClasses::Class_klass()) {
4288 st->print(BULLET"signature: ");
4289 java_lang_Class::print_signature(obj, st);
4290 st->cr();
4291 Klass* real_klass = java_lang_Class::as_Klass(obj);
4292 if (real_klass != nullptr && real_klass->is_instance_klass()) {
4293 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj));
4294 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
4295 }
4296 } else if (this == vmClasses::MethodType_klass()) {
4297 st->print(BULLET"signature: ");
4298 java_lang_invoke_MethodType::print_signature(obj, st);
4299 st->cr();
4300 }
4301 }
4302
4303 #ifndef PRODUCT
4304
|