46 #include "compiler/compileBroker.hpp"
47 #include "gc/shared/collectedHeap.inline.hpp"
48 #include "interpreter/bytecodeStream.hpp"
49 #include "interpreter/oopMapCache.hpp"
50 #include "interpreter/rewriter.hpp"
51 #include "jvm.h"
52 #include "jvmtifiles/jvmti.h"
53 #include "klass.inline.hpp"
54 #include "logging/log.hpp"
55 #include "logging/logMessage.hpp"
56 #include "logging/logStream.hpp"
57 #include "memory/allocation.inline.hpp"
58 #include "memory/iterator.inline.hpp"
59 #include "memory/metadataFactory.hpp"
60 #include "memory/metaspaceClosure.hpp"
61 #include "memory/oopFactory.hpp"
62 #include "memory/resourceArea.hpp"
63 #include "memory/universe.hpp"
64 #include "oops/constantPool.hpp"
65 #include "oops/fieldStreams.inline.hpp"
66 #include "oops/instanceClassLoaderKlass.hpp"
67 #include "oops/instanceKlass.inline.hpp"
68 #include "oops/instanceMirrorKlass.hpp"
69 #include "oops/instanceOop.hpp"
70 #include "oops/instanceStackChunkKlass.hpp"
71 #include "oops/klass.inline.hpp"
72 #include "oops/method.hpp"
73 #include "oops/oop.inline.hpp"
74 #include "oops/recordComponent.hpp"
75 #include "oops/symbol.hpp"
76 #include "prims/jvmtiExport.hpp"
77 #include "prims/jvmtiRedefineClasses.hpp"
78 #include "prims/jvmtiThreadState.hpp"
79 #include "prims/methodComparator.hpp"
80 #include "runtime/arguments.hpp"
81 #include "runtime/atomicAccess.hpp"
82 #include "runtime/deoptimization.hpp"
83 #include "runtime/fieldDescriptor.inline.hpp"
84 #include "runtime/handles.inline.hpp"
85 #include "runtime/javaCalls.hpp"
86 #include "runtime/javaThread.inline.hpp"
87 #include "runtime/mutexLocker.hpp"
88 #include "runtime/orderAccess.hpp"
89 #include "runtime/os.inline.hpp"
90 #include "runtime/reflection.hpp"
91 #include "runtime/synchronizer.hpp"
92 #include "runtime/threads.hpp"
93 #include "services/classLoadingService.hpp"
94 #include "services/finalizerService.hpp"
95 #include "services/threadService.hpp"
96 #include "utilities/dtrace.hpp"
97 #include "utilities/events.hpp"
98 #include "utilities/macros.hpp"
99 #include "utilities/nativeStackPrinter.hpp"
100 #include "utilities/stringUtils.hpp"
101 #ifdef COMPILER1
102 #include "c1/c1_Compiler.hpp"
103 #endif
104 #if INCLUDE_JFR
105 #include "jfr/jfrEvents.hpp"
106 #endif
107
108 #ifdef DTRACE_ENABLED
109
110
111 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
112 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
113 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
114 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
115 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
116 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
117 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
118 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
119 #define DTRACE_CLASSINIT_PROBE(type, thread_type) \
132 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait) \
133 { \
134 char* data = nullptr; \
135 int len = 0; \
136 Symbol* clss_name = name(); \
137 if (clss_name != nullptr) { \
138 data = (char*)clss_name->bytes(); \
139 len = clss_name->utf8_length(); \
140 } \
141 HOTSPOT_CLASS_INITIALIZATION_##type( \
142 data, len, (void*)class_loader(), thread_type, wait); \
143 }
144
145 #else // ndef DTRACE_ENABLED
146
147 #define DTRACE_CLASSINIT_PROBE(type, thread_type)
148 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)
149
150 #endif // ndef DTRACE_ENABLED
151
152 bool InstanceKlass::_finalization_enabled = true;
153
154 static inline bool is_class_loader(const Symbol* class_name,
155 const ClassFileParser& parser) {
156 assert(class_name != nullptr, "invariant");
157
158 if (class_name == vmSymbols::java_lang_ClassLoader()) {
159 return true;
160 }
161
162 if (vmClasses::ClassLoader_klass_is_loaded()) {
163 const Klass* const super_klass = parser.super_klass();
164 if (super_klass != nullptr) {
165 if (super_klass->is_subtype_of(vmClasses::ClassLoader_klass())) {
166 return true;
167 }
168 }
169 }
170 return false;
171 }
172
173 static inline bool is_stack_chunk_class(const Symbol* class_name,
174 const ClassLoaderData* loader_data) {
175 return (class_name == vmSymbols::jdk_internal_vm_StackChunk() &&
176 loader_data->is_the_null_class_loader_data());
177 }
178
179 // private: called to verify that k is a static member of this nest.
180 // We know that k is an instance class in the same package and hence the
181 // same classloader.
182 bool InstanceKlass::has_nest_member(JavaThread* current, InstanceKlass* k) const {
183 assert(!is_hidden(), "unexpected hidden class");
184 if (_nest_members == nullptr || _nest_members == Universe::the_empty_short_array()) {
185 if (log_is_enabled(Trace, class, nestmates)) {
186 ResourceMark rm(current);
187 log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
188 k->external_name(), this->external_name());
189 }
190 return false;
191 }
192
440 log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
441 this->external_name(),
442 access ? "" : "NOT ",
443 k->external_name());
444 return access;
445 }
446
447 const char* InstanceKlass::nest_host_error() {
448 if (_nest_host_index == 0) {
449 return nullptr;
450 } else {
451 constantPoolHandle cph(Thread::current(), constants());
452 return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index);
453 }
454 }
455
456 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
457 const int size = InstanceKlass::size(parser.vtable_size(),
458 parser.itable_size(),
459 nonstatic_oop_map_size(parser.total_oop_map_count()),
460 parser.is_interface());
461
462 const Symbol* const class_name = parser.class_name();
463 assert(class_name != nullptr, "invariant");
464 ClassLoaderData* loader_data = parser.loader_data();
465 assert(loader_data != nullptr, "invariant");
466
467 InstanceKlass* ik;
468
469 // Allocation
470 if (parser.is_instance_ref_klass()) {
471 // java.lang.ref.Reference
472 ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
473 } else if (class_name == vmSymbols::java_lang_Class()) {
474 // mirror - java.lang.Class
475 ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
476 } else if (is_stack_chunk_class(class_name, loader_data)) {
477 // stack chunk
478 ik = new (loader_data, size, THREAD) InstanceStackChunkKlass(parser);
479 } else if (is_class_loader(class_name, parser)) {
480 // class loader - java.lang.ClassLoader
481 ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);
482 } else {
483 // normal
484 ik = new (loader_data, size, THREAD) InstanceKlass(parser);
485 }
486
487 if (ik != nullptr && UseCompressedClassPointers) {
488 assert(CompressedKlassPointers::is_encodable(ik),
489 "Klass " PTR_FORMAT "needs a narrow Klass ID, but is not encodable", p2i(ik));
490 }
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 MetadataFactory::free_metadata(loader_data, constants());
708 }
709 // Delete any cached resolution errors for the constant pool
710 SystemDictionary::delete_resolution_error(constants());
711
712 set_constants(nullptr);
713 }
714
715 if (inner_classes() != nullptr &&
716 inner_classes() != Universe::the_empty_short_array() &&
717 !inner_classes()->in_aot_cache()) {
718 MetadataFactory::free_array<jushort>(loader_data, inner_classes());
719 }
720 set_inner_classes(nullptr);
721
722 if (nest_members() != nullptr &&
723 nest_members() != Universe::the_empty_short_array() &&
724 !nest_members()->in_aot_cache()) {
725 MetadataFactory::free_array<jushort>(loader_data, nest_members());
726 }
727 set_nest_members(nullptr);
728
729 if (permitted_subclasses() != nullptr &&
730 permitted_subclasses() != Universe::the_empty_short_array() &&
731 !permitted_subclasses()->in_aot_cache()) {
732 MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
733 }
734 set_permitted_subclasses(nullptr);
735
736 // We should deallocate the Annotations instance if it's not in shared spaces.
737 if (annotations() != nullptr && !annotations()->in_aot_cache()) {
738 MetadataFactory::free_metadata(loader_data, annotations());
739 }
740 set_annotations(nullptr);
741
742 SystemDictionaryShared::handle_class_unloading(this);
743
744 #if INCLUDE_CDS_JAVA_HEAP
745 if (CDSConfig::is_dumping_heap()) {
746 HeapShared::remove_scratch_objects(this);
747 }
748 #endif
749 }
750
751 bool InstanceKlass::is_record() const {
752 return _record_components != nullptr &&
753 is_final() &&
754 super() == vmClasses::Record_klass();
755 }
758 return _permitted_subclasses != nullptr &&
759 _permitted_subclasses != Universe::the_empty_short_array();
760 }
761
762 // JLS 8.9: An enum class is either implicitly final and derives
763 // from java.lang.Enum, or else is implicitly sealed to its
764 // anonymous subclasses. This query detects both kinds.
765 // It does not validate the finality or
766 // sealing conditions: it merely checks for a super of Enum.
767 // This is sufficient for recognizing well-formed enums.
768 bool InstanceKlass::is_enum_subclass() const {
769 InstanceKlass* s = super();
770 return (s == vmClasses::Enum_klass() ||
771 (s != nullptr && s->super() == vmClasses::Enum_klass()));
772 }
773
774 bool InstanceKlass::should_be_initialized() const {
775 return !is_initialized();
776 }
777
778 klassItable InstanceKlass::itable() const {
779 return klassItable(const_cast<InstanceKlass*>(this));
780 }
781
782 // JVMTI spec thinks there are signers and protection domain in the
783 // instanceKlass. These accessors pretend these fields are there.
784 // The hprof specification also thinks these fields are in InstanceKlass.
785 oop InstanceKlass::protection_domain() const {
786 // return the protection_domain from the mirror
787 return java_lang_Class::protection_domain(java_mirror());
788 }
789
790 objArrayOop InstanceKlass::signers() const {
791 // return the signers from the mirror
792 return java_lang_Class::signers(java_mirror());
793 }
794
795 oop InstanceKlass::init_lock() const {
796 // return the init lock from the mirror
797 oop lock = java_lang_Class::init_lock(java_mirror());
910 #ifdef ASSERT
911 {
912 Handle h_init_lock(THREAD, init_lock());
913 ObjectLocker ol(h_init_lock, THREAD);
914 assert(!is_initialized(), "sanity");
915 assert(!is_being_initialized(), "sanity");
916 assert(!is_in_error_state(), "sanity");
917 }
918 #endif
919
920 set_init_thread(THREAD);
921 set_initialization_state_and_notify(fully_initialized, CHECK);
922 }
923 #endif
924
925 bool InstanceKlass::verify_code(TRAPS) {
926 // 1) Verify the bytecodes
927 return Verifier::verify(this, should_verify_class(), THREAD);
928 }
929
930 void InstanceKlass::link_class(TRAPS) {
931 assert(is_loaded(), "must be loaded");
932 if (!is_linked()) {
933 link_class_impl(CHECK);
934 }
935 }
936
937 // Called to verify that a class can link during initialization, without
938 // throwing a VerifyError.
939 bool InstanceKlass::link_class_or_fail(TRAPS) {
940 assert(is_loaded(), "must be loaded");
941 if (!is_linked()) {
942 link_class_impl(CHECK_false);
943 }
944 return is_linked();
945 }
946
947 bool InstanceKlass::link_class_impl(TRAPS) {
948 if (CDSConfig::is_dumping_static_archive() && SystemDictionaryShared::has_class_failed_verification(this)) {
949 // This is for CDS static dump only -- we use the in_error_state to indicate that
980 THREAD_AND_LOCATION,
981 vmSymbols::java_lang_IncompatibleClassChangeError(),
982 "class %s has interface %s as super class",
983 external_name(),
984 super_klass->external_name()
985 );
986 return false;
987 }
988
989 super_klass->link_class_impl(CHECK_false);
990 }
991
992 // link all interfaces implemented by this class before linking this class
993 Array<InstanceKlass*>* interfaces = local_interfaces();
994 int num_interfaces = interfaces->length();
995 for (int index = 0; index < num_interfaces; index++) {
996 InstanceKlass* interk = interfaces->at(index);
997 interk->link_class_impl(CHECK_false);
998 }
999
1000 // in case the class is linked in the process of linking its superclasses
1001 if (is_linked()) {
1002 return true;
1003 }
1004
1005 // trace only the link time for this klass that includes
1006 // the verification time
1007 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
1008 ClassLoader::perf_class_link_selftime(),
1009 ClassLoader::perf_classes_linked(),
1010 jt->get_thread_stat()->perf_recursion_counts_addr(),
1011 jt->get_thread_stat()->perf_timers_addr(),
1012 PerfClassTraceTime::CLASS_LINK);
1013
1014 // verification & rewriting
1015 {
1016 HandleMark hm(THREAD);
1017 Handle h_init_lock(THREAD, init_lock());
1018 ObjectLocker ol(h_init_lock, CHECK_PREEMPTABLE_false);
1019 // Don't allow preemption if we link/initialize classes below,
1303 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1304 ss.as_string(), cause);
1305 }
1306 } else {
1307
1308 // Step 6
1309 set_init_state(being_initialized);
1310 set_init_thread(jt);
1311 if (debug_logging_enabled) {
1312 ResourceMark rm(jt);
1313 log_debug(class, init)("Thread \"%s\" is initializing %s",
1314 jt->name(), external_name());
1315 }
1316 }
1317 }
1318
1319 // Block preemption once we are the initializer thread. Unmounting now
1320 // would complicate the reentrant case (identity is platform thread).
1321 NoPreemptMark npm(THREAD);
1322
1323 // Step 7
1324 // Next, if C is a class rather than an interface, initialize it's super class and super
1325 // interfaces.
1326 if (!is_interface()) {
1327 Klass* super_klass = super();
1328 if (super_klass != nullptr && super_klass->should_be_initialized()) {
1329 super_klass->initialize(THREAD);
1330 }
1331 // If C implements any interface that declares a non-static, concrete method,
1332 // the initialization of C triggers initialization of its super interfaces.
1333 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1334 // having a superinterface that declares, non-static, concrete methods
1335 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1336 initialize_super_interfaces(THREAD);
1337 }
1338
1339 // If any exceptions, complete abruptly, throwing the same exception as above.
1340 if (HAS_PENDING_EXCEPTION) {
1341 Handle e(THREAD, PENDING_EXCEPTION);
1342 CLEAR_PENDING_EXCEPTION;
1343 {
1344 EXCEPTION_MARK;
1345 add_initialization_error(THREAD, e);
1346 // Locks object, set state, and notify all waiting threads
1347 set_initialization_state_and_notify(initialization_error, THREAD);
1348 CLEAR_PENDING_EXCEPTION;
1349 }
1350 DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1351 THROW_OOP(e());
1352 }
1353 }
1354
1355
1356 // Step 8
1357 {
1358 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1359 if (class_initializer() != nullptr) {
1360 // Timer includes any side effects of class initialization (resolution,
1361 // etc), but not recursive entry into call_class_initializer().
1362 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1363 ClassLoader::perf_class_init_selftime(),
1364 ClassLoader::perf_classes_inited(),
1365 jt->get_thread_stat()->perf_recursion_counts_addr(),
1366 jt->get_thread_stat()->perf_timers_addr(),
1367 PerfClassTraceTime::CLASS_CLINIT);
1368 call_class_initializer(THREAD);
1369 } else {
1370 // The elapsed time is so small it's not worth counting.
1371 if (UsePerfData) {
1372 ClassLoader::perf_classes_inited()->inc();
1373 }
1374 call_class_initializer(THREAD);
1375 }
1376 }
1377
1378 // Step 9
1379 if (!HAS_PENDING_EXCEPTION) {
1380 set_initialization_state_and_notify(fully_initialized, CHECK);
1381 DEBUG_ONLY(vtable().verify(tty, true);)
1382 CompilationPolicy::replay_training_at_init(this, THREAD);
1383 }
1384 else {
1385 // Step 10 and 11
1386 Handle e(THREAD, PENDING_EXCEPTION);
1387 CLEAR_PENDING_EXCEPTION;
1388 // JVMTI has already reported the pending exception
1389 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1390 JvmtiExport::clear_detected_exception(jt);
1391 {
1392 EXCEPTION_MARK;
1393 add_initialization_error(THREAD, e);
1394 set_initialization_state_and_notify(initialization_error, THREAD);
1395 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1409 }
1410 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1411 }
1412
1413
1414 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1415 Handle h_init_lock(THREAD, init_lock());
1416 if (h_init_lock() != nullptr) {
1417 ObjectLocker ol(h_init_lock, THREAD);
1418 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1419 set_init_state(state);
1420 fence_and_clear_init_lock();
1421 ol.notify_all(CHECK);
1422 } else {
1423 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1424 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1425 set_init_state(state);
1426 }
1427 }
1428
1429 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1430 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1431 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1432 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1433
1434 DeoptimizationScope deopt_scope;
1435 {
1436 MutexLocker ml(current, Compile_lock);
1437
1438 set_init_state(InstanceKlass::loaded);
1439 // make sure init_state store is already done.
1440 // The compiler reads the hierarchy outside of the Compile_lock.
1441 // Access ordering is used to add to hierarchy.
1442
1443 // Link into hierarchy.
1444 append_to_sibling_list(); // add to superklass/sibling list
1445 process_interfaces(); // handle all "implements" declarations
1446
1447 // Now mark all code that depended on old class hierarchy.
1448 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1659 : vmSymbols::java_lang_IllegalAccessException(), external_name());
1660 }
1661 }
1662
1663 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
1664 // Need load-acquire for lock-free read
1665 if (array_klasses_acquire() == nullptr) {
1666
1667 // Recursively lock array allocation
1668 RecursiveLocker rl(MultiArray_lock, THREAD);
1669
1670 // Check if another thread created the array klass while we were waiting for the lock.
1671 if (array_klasses() == nullptr) {
1672 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
1673 // use 'release' to pair with lock-free load
1674 release_set_array_klasses(k);
1675 }
1676 }
1677
1678 // array_klasses() will always be set at this point
1679 ObjArrayKlass* ak = array_klasses();
1680 assert(ak != nullptr, "should be set");
1681 return ak->array_klass(n, THREAD);
1682 }
1683
1684 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1685 // Need load-acquire for lock-free read
1686 ObjArrayKlass* oak = array_klasses_acquire();
1687 if (oak == nullptr) {
1688 return nullptr;
1689 } else {
1690 return oak->array_klass_or_null(n);
1691 }
1692 }
1693
1694 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1695 return array_klass(1, THREAD);
1696 }
1697
1698 ArrayKlass* InstanceKlass::array_klass_or_null() {
1699 return array_klass_or_null(1);
1700 }
1701
1702 static int call_class_initializer_counter = 0; // for debugging
1703
1704 Method* InstanceKlass::class_initializer() const {
1705 Method* clinit = find_method(
1706 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1707 if (clinit != nullptr && clinit->has_valid_initializer_flags()) {
1708 return clinit;
1709 }
1710 return nullptr;
1711 }
1712
1713 void InstanceKlass::call_class_initializer(TRAPS) {
1714 if (ReplayCompiles &&
1715 (ReplaySuppressInitializers == 1 ||
1716 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1717 // Hide the existence of the initializer for the purpose of replaying the compile
1718 return;
1719 }
1720
1721 #if INCLUDE_CDS
1722 // This is needed to ensure the consistency of the archived heap objects.
1723 if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
1724 AOTClassInitializer::call_runtime_setup(THREAD, this);
1725 return;
1726 } else if (has_archived_enum_objs()) {
1727 assert(in_aot_cache(), "must be");
1796
1797 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1798 InterpreterOopMap* entry_for) {
1799 // Lazily create the _oop_map_cache at first request.
1800 // Load_acquire is needed to safely get instance published with CAS by another thread.
1801 OopMapCache* oop_map_cache = AtomicAccess::load_acquire(&_oop_map_cache);
1802 if (oop_map_cache == nullptr) {
1803 // Try to install new instance atomically.
1804 oop_map_cache = new OopMapCache();
1805 OopMapCache* other = AtomicAccess::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
1806 if (other != nullptr) {
1807 // Someone else managed to install before us, ditch local copy and use the existing one.
1808 delete oop_map_cache;
1809 oop_map_cache = other;
1810 }
1811 }
1812 // _oop_map_cache is constant after init; lookup below does its own locking.
1813 oop_map_cache->lookup(method, bci, entry_for);
1814 }
1815
1816 bool InstanceKlass::contains_field_offset(int offset) {
1817 fieldDescriptor fd;
1818 return find_field_from_offset(offset, false, &fd);
1819 }
1820
1821 FieldInfo InstanceKlass::field(int index) const {
1822 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
1823 if (fs.index() == index) {
1824 return fs.to_FieldInfo();
1825 }
1826 }
1827 fatal("Field not found");
1828 return FieldInfo();
1829 }
1830
1831 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1832 JavaFieldStream fs(this);
1833 if (fs.lookup(name, sig)) {
1834 assert(fs.name() == name, "name must match");
1835 assert(fs.signature() == sig, "signature must match");
1836 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
1837 return true;
1838 }
1839 return false;
1880
1881 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1882 // search order according to newest JVM spec (5.4.3.2, p.167).
1883 // 1) search for field in current klass
1884 if (find_local_field(name, sig, fd)) {
1885 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1886 }
1887 // 2) search for field recursively in direct superinterfaces
1888 if (is_static) {
1889 Klass* intf = find_interface_field(name, sig, fd);
1890 if (intf != nullptr) return intf;
1891 }
1892 // 3) apply field lookup recursively if superclass exists
1893 { InstanceKlass* supr = super();
1894 if (supr != nullptr) return supr->find_field(name, sig, is_static, fd);
1895 }
1896 // 4) otherwise field lookup fails
1897 return nullptr;
1898 }
1899
1900
1901 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1902 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1903 if (fs.offset() == offset) {
1904 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
1905 if (fd->is_static() == is_static) return true;
1906 }
1907 }
1908 return false;
1909 }
1910
1911
1912 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1913 const InstanceKlass* klass = this;
1914 while (klass != nullptr) {
1915 if (klass->find_local_field_from_offset(offset, is_static, fd)) {
1916 return true;
1917 }
1918 klass = klass->super();
1919 }
1920 return false;
1921 }
1922
1923
1924 void InstanceKlass::methods_do(void f(Method* method)) {
1925 // Methods aren't stable until they are loaded. This can be read outside
1926 // a lock through the ClassLoaderData for profiling
1927 // Redefined scratch classes are on the list and need to be cleaned
1928 if (!is_loaded() && !is_scratch_class()) {
1929 return;
1930 }
1931
1932 int len = methods()->length();
1933 for (int index = 0; index < len; index++) {
1934 Method* m = methods()->at(index);
1935 assert(m->is_method(), "must be method");
1936 f(m);
1937 }
1938 }
1939
1940
1941 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
1942 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1943 if (fs.access_flags().is_static()) {
1944 fieldDescriptor& fd = fs.field_descriptor();
1945 cl->do_field(&fd);
1946 }
1947 }
1948 }
1949
1950
1951 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
1952 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1953 if (fs.access_flags().is_static()) {
1954 fieldDescriptor& fd = fs.field_descriptor();
1955 f(&fd, mirror, CHECK);
1956 }
1957 }
1958 }
1959
1960 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
1961 InstanceKlass* super = this->super();
1962 if (super != nullptr) {
1963 super->do_nonstatic_fields(cl);
1964 }
1965 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1966 fieldDescriptor& fd = fs.field_descriptor();
1967 if (!fd.is_static()) {
1968 cl->do_field(&fd);
1969 }
1970 }
1971 }
1972
2263 }
2264
2265 // uncached_lookup_method searches both the local class methods array and all
2266 // superclasses methods arrays, skipping any overpass methods in superclasses,
2267 // and possibly skipping private methods.
2268 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2269 const Symbol* signature,
2270 OverpassLookupMode overpass_mode,
2271 PrivateLookupMode private_mode) const {
2272 OverpassLookupMode overpass_local_mode = overpass_mode;
2273 const InstanceKlass* klass = this;
2274 while (klass != nullptr) {
2275 Method* const method = klass->find_method_impl(name,
2276 signature,
2277 overpass_local_mode,
2278 StaticLookupMode::find,
2279 private_mode);
2280 if (method != nullptr) {
2281 return method;
2282 }
2283 klass = klass->super();
2284 overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses
2285 }
2286 return nullptr;
2287 }
2288
2289 #ifdef ASSERT
2290 // search through class hierarchy and return true if this class or
2291 // one of the superclasses was redefined
2292 bool InstanceKlass::has_redefined_this_or_super() const {
2293 const InstanceKlass* klass = this;
2294 while (klass != nullptr) {
2295 if (klass->has_been_redefined()) {
2296 return true;
2297 }
2298 klass = klass->super();
2299 }
2300 return false;
2301 }
2302 #endif
2675 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2676
2677 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2678 / itableOffsetEntry::size();
2679
2680 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2681 if (ioe->interface_klass() != nullptr) {
2682 it->push(ioe->interface_klass_addr());
2683 itableMethodEntry* ime = ioe->first_method_entry(this);
2684 int n = klassItable::method_count_for_interface(ioe->interface_klass());
2685 for (int index = 0; index < n; index ++) {
2686 it->push(ime[index].method_addr());
2687 }
2688 }
2689 }
2690 }
2691
2692 it->push(&_nest_host);
2693 it->push(&_nest_members);
2694 it->push(&_permitted_subclasses);
2695 it->push(&_record_components);
2696
2697 if (CDSConfig::is_dumping_full_module_graph() && !defined_by_other_loaders()) {
2698 it->push(&_package_entry);
2699 }
2700 }
2701
2702 #if INCLUDE_CDS
2703 void InstanceKlass::remove_unshareable_info() {
2704
2705 if (is_linked()) {
2706 assert(can_be_verified_at_dumptime(), "must be");
2707 // Remember this so we can avoid walking the hierarchy at runtime.
2708 set_verified_at_dump_time();
2709 }
2710
2711 _misc_flags.set_has_init_deps_processed(false);
2712
2713 Klass::remove_unshareable_info();
2714
2715 if (SystemDictionaryShared::has_class_failed_verification(this)) {
2727
2728 { // Otherwise this needs to take out the Compile_lock.
2729 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2730 init_implementor();
2731 }
2732
2733 // Call remove_unshareable_info() on other objects that belong to this class, except
2734 // for constants()->remove_unshareable_info(), which is called in a separate pass in
2735 // ArchiveBuilder::make_klasses_shareable(),
2736
2737 for (int i = 0; i < methods()->length(); i++) {
2738 Method* m = methods()->at(i);
2739 m->remove_unshareable_info();
2740 }
2741
2742 // do array classes also.
2743 if (array_klasses() != nullptr) {
2744 array_klasses()->remove_unshareable_info();
2745 }
2746
2747 // These are not allocated from metaspace. They are safe to set to null.
2748 _source_debug_extension = nullptr;
2749 _dep_context = nullptr;
2750 _osr_nmethods_head = nullptr;
2751 #if INCLUDE_JVMTI
2752 _breakpoints = nullptr;
2753 _previous_versions = nullptr;
2754 _cached_class_file = nullptr;
2755 _jvmti_cached_class_field_map = nullptr;
2756 #endif
2757
2758 _init_thread = nullptr;
2759 _methods_jmethod_ids = nullptr;
2760 _jni_ids = nullptr;
2761 _oop_map_cache = nullptr;
2762 if (CDSConfig::is_dumping_method_handles() && HeapShared::is_lambda_proxy_klass(this)) {
2763 // keep _nest_host
2764 } else {
2765 // clear _nest_host to ensure re-load at runtime
2766 _nest_host = nullptr;
2767 }
2803 void InstanceKlass::compute_has_loops_flag_for_methods() {
2804 Array<Method*>* methods = this->methods();
2805 for (int index = 0; index < methods->length(); ++index) {
2806 Method* m = methods->at(index);
2807 if (!m->is_overpass()) { // work around JDK-8305771
2808 m->compute_has_loops_flag();
2809 }
2810 }
2811 }
2812
2813 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
2814 PackageEntry* pkg_entry, TRAPS) {
2815 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
2816 // before the InstanceKlass is added to the SystemDictionary. Make
2817 // sure the current state is <loaded.
2818 assert(!is_loaded(), "invalid init state");
2819 assert(!shared_loading_failed(), "Must not try to load failed class again");
2820 set_package(loader_data, pkg_entry, CHECK);
2821 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2822
2823 Array<Method*>* methods = this->methods();
2824 int num_methods = methods->length();
2825 for (int index = 0; index < num_methods; ++index) {
2826 methods->at(index)->restore_unshareable_info(CHECK);
2827 }
2828 #if INCLUDE_JVMTI
2829 if (JvmtiExport::has_redefined_a_class()) {
2830 // Reinitialize vtable because RedefineClasses may have changed some
2831 // entries in this vtable for super classes so the CDS vtable might
2832 // point to old or obsolete entries. RedefineClasses doesn't fix up
2833 // vtables in the shared system dictionary, only the main one.
2834 // It also redefines the itable too so fix that too.
2835 // First fix any default methods that point to a super class that may
2836 // have been redefined.
2837 bool trace_name_printed = false;
2838 adjust_default_methods(&trace_name_printed);
2839 if (verified_at_dump_time()) {
2840 // Initialize vtable and itable for classes which can be verified at dump time.
2841 // Unlinked classes such as old classes with major version < 50 cannot be verified
2842 // at dump time.
2843 vtable().initialize_vtable();
2844 itable().initialize_itable();
2845 }
2846 }
2847 #endif // INCLUDE_JVMTI
2848
2849 // restore constant pool resolved references
2850 constants()->restore_unshareable_info(CHECK);
2851
2852 if (array_klasses() != nullptr) {
2853 // To get a consistent list of classes we need MultiArray_lock to ensure
2854 // array classes aren't observed while they are being restored.
2855 RecursiveLocker rl(MultiArray_lock, THREAD);
2856 assert(this == array_klasses()->bottom_klass(), "sanity");
2857 // Array classes have null protection domain.
2858 // --> see ArrayKlass::complete_create_array_klass()
2859 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
2860 }
2861
2862 // Initialize @ValueBased class annotation if not already set in the archived klass.
2863 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
2864 set_is_value_based();
2865 }
2866
2867 DEBUG_ONLY(FieldInfoStream::validate_search_table(_constants, _fieldinfo_stream, _fieldinfo_search_table));
2868 }
2869
2870 bool InstanceKlass::can_be_verified_at_dumptime() const {
2871 if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(this)) {
2872 // This is a class that was dumped into the base archive, so we know
2873 // it was verified at dump time.
2874 return true;
2875 }
2876
2877 if (CDSConfig::is_preserving_verification_constraints()) {
2878 return true;
2994 constants()->release_C_heap_structures();
2995 }
2996 }
2997
2998 // The constant pool is on stack if any of the methods are executing or
2999 // referenced by handles.
3000 bool InstanceKlass::on_stack() const {
3001 return _constants->on_stack();
3002 }
3003
3004 Symbol* InstanceKlass::source_file_name() const { return _constants->source_file_name(); }
3005 u2 InstanceKlass::source_file_name_index() const { return _constants->source_file_name_index(); }
3006 void InstanceKlass::set_source_file_name_index(u2 sourcefile_index) { _constants->set_source_file_name_index(sourcefile_index); }
3007
3008 // minor and major version numbers of class file
3009 u2 InstanceKlass::minor_version() const { return _constants->minor_version(); }
3010 void InstanceKlass::set_minor_version(u2 minor_version) { _constants->set_minor_version(minor_version); }
3011 u2 InstanceKlass::major_version() const { return _constants->major_version(); }
3012 void InstanceKlass::set_major_version(u2 major_version) { _constants->set_major_version(major_version); }
3013
3014 const InstanceKlass* InstanceKlass::get_klass_version(int version) const {
3015 for (const InstanceKlass* ik = this; ik != nullptr; ik = ik->previous_versions()) {
3016 if (ik->constants()->version() == version) {
3017 return ik;
3018 }
3019 }
3020 return nullptr;
3021 }
3022
3023 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
3024 if (array == nullptr) {
3025 _source_debug_extension = nullptr;
3026 } else {
3027 // Adding one to the attribute length in order to store a null terminator
3028 // character could cause an overflow because the attribute length is
3029 // already coded with an u4 in the classfile, but in practice, it's
3030 // unlikely to happen.
3031 assert((length+1) > length, "Overflow checking");
3032 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
3033 for (int i = 0; i < length; i++) {
3034 sde[i] = array[i];
3035 }
3036 sde[length] = '\0';
3037 _source_debug_extension = sde;
3038 }
3039 }
3040
3041 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); }
3042 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); }
3043 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); }
3044
3045 const char* InstanceKlass::signature_name() const {
3046
3047 // Get the internal name as a c string
3048 const char* src = (const char*) (name()->as_C_string());
3049 const int src_length = (int)strlen(src);
3050
3051 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
3052
3053 // Add L as type indicator
3054 int dest_index = 0;
3055 dest[dest_index++] = JVM_SIGNATURE_CLASS;
3056
3057 // Add the actual class name
3058 for (int src_index = 0; src_index < src_length; ) {
3059 dest[dest_index++] = src[src_index++];
3060 }
3061
3062 if (is_hidden()) { // Replace the last '+' with a '.'.
3063 for (int index = (int)src_length; index > 0; index--) {
3064 if (dest[index] == '+') {
3065 dest[index] = JVM_SIGNATURE_DOT;
3066 break;
3067 }
3068 }
3069 }
3070
3071 // Add the semicolon and the null
3072 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3073 dest[dest_index] = '\0';
3074 return dest;
3075 }
3316 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3317 constantPoolHandle i_cp(THREAD, constants());
3318 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3319 int ioff = iter.inner_class_info_index();
3320 if (ioff != 0) {
3321 // Check to see if the name matches the class we're looking for
3322 // before attempting to find the class.
3323 if (i_cp->klass_name_at_matches(this, ioff)) {
3324 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3325 if (this == inner_klass) {
3326 *ooff = iter.outer_class_info_index();
3327 *noff = iter.inner_name_index();
3328 return true;
3329 }
3330 }
3331 }
3332 }
3333 return false;
3334 }
3335
3336 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3337 InstanceKlass* outer_klass = nullptr;
3338 *inner_is_member = false;
3339 int ooff = 0, noff = 0;
3340 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3341 if (has_inner_classes_attr) {
3342 constantPoolHandle i_cp(THREAD, constants());
3343 if (ooff != 0) {
3344 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3345 if (!ok->is_instance_klass()) {
3346 // If the outer class is not an instance klass then it cannot have
3347 // declared any inner classes.
3348 ResourceMark rm(THREAD);
3349 // Names are all known to be < 64k so we know this formatted message is not excessively large.
3350 Exceptions::fthrow(
3351 THREAD_AND_LOCATION,
3352 vmSymbols::java_lang_IncompatibleClassChangeError(),
3353 "%s and %s disagree on InnerClasses attribute",
3354 ok->external_name(),
3355 external_name());
3382 u2 InstanceKlass::compute_modifier_flags() const {
3383 u2 access = access_flags().as_unsigned_short();
3384
3385 // But check if it happens to be member class.
3386 InnerClassesIterator iter(this);
3387 for (; !iter.done(); iter.next()) {
3388 int ioff = iter.inner_class_info_index();
3389 // Inner class attribute can be zero, skip it.
3390 // Strange but true: JVM spec. allows null inner class refs.
3391 if (ioff == 0) continue;
3392
3393 // only look at classes that are already loaded
3394 // since we are looking for the flags for our self.
3395 Symbol* inner_name = constants()->klass_name_at(ioff);
3396 if (name() == inner_name) {
3397 // This is really a member class.
3398 access = iter.inner_access_flags();
3399 break;
3400 }
3401 }
3402 // Remember to strip ACC_SUPER bit
3403 return (access & (~JVM_ACC_SUPER));
3404 }
3405
3406 jint InstanceKlass::jvmti_class_status() const {
3407 jint result = 0;
3408
3409 if (is_linked()) {
3410 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3411 }
3412
3413 if (is_initialized()) {
3414 assert(is_linked(), "Class status is not consistent");
3415 result |= JVMTI_CLASS_STATUS_INITIALIZED;
3416 }
3417 if (is_in_error_state()) {
3418 result |= JVMTI_CLASS_STATUS_ERROR;
3419 }
3420 return result;
3421 }
3422
3423 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
3637 }
3638 osr = osr->osr_link();
3639 }
3640
3641 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
3642 if (best != nullptr && best->comp_level() >= comp_level) {
3643 return best;
3644 }
3645 return nullptr;
3646 }
3647
3648 // -----------------------------------------------------------------------------------------------------
3649 // Printing
3650
3651 #define BULLET " - "
3652
3653 static const char* state_names[] = {
3654 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3655 };
3656
3657 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3658 for (int i = 0; i < len; i++) {
3659 intptr_t e = start[i];
3660 st->print("%d : " INTPTR_FORMAT, i, e);
3661 if (MetaspaceObj::is_valid((Metadata*)e)) {
3662 st->print(" ");
3663 ((Metadata*)e)->print_value_on(st);
3664 }
3665 st->cr();
3666 }
3667 }
3668
3669 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3670 return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3671 }
3672
3673 const char* InstanceKlass::init_state_name() const {
3674 return state_names[init_state()];
3675 }
3676
3677 void InstanceKlass::print_on(outputStream* st) const {
3678 assert(is_klass(), "must be klass");
3679 Klass::print_on(st);
3680
3681 st->print(BULLET"instance size: %d", size_helper()); st->cr();
3682 st->print(BULLET"klass size: %d", size()); st->cr();
3683 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
3684 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
3685 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
3686 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
3687 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3688 st->print(BULLET"sub: ");
3689 Klass* sub = subklass();
3690 int n;
3691 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3692 if (n < MaxSubklassPrintSize) {
3693 sub->print_value_on(st);
3694 st->print(" ");
3695 }
3696 }
3697 if (n >= MaxSubklassPrintSize) st->print("(%zd more klasses...)", n - MaxSubklassPrintSize);
3698 st->cr();
3699
3700 if (is_interface()) {
3701 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
3702 if (nof_implementors() == 1) {
3703 st->print_cr(BULLET"implementor: ");
3704 st->print(" ");
3705 implementor()->print_value_on(st);
3706 st->cr();
3707 }
3708 }
3709
3710 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3711 st->print(BULLET"methods: "); methods()->print_value_on(st); st->cr();
3712 if (Verbose || WizardMode) {
3713 Array<Method*>* method_array = methods();
3714 for (int i = 0; i < method_array->length(); i++) {
3715 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3716 }
3717 }
3718 st->print(BULLET"method ordering: "); method_ordering()->print_value_on(st); st->cr();
3719 if (default_methods() != nullptr) {
3720 st->print(BULLET"default_methods: "); default_methods()->print_value_on(st); st->cr();
3721 if (Verbose) {
3722 Array<Method*>* method_array = default_methods();
3723 for (int i = 0; i < method_array->length(); i++) {
3724 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3725 }
3726 }
3727 }
3728 print_on_maybe_null(st, BULLET"default vtable indices: ", default_vtable_indices());
3729 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
3730 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3731
3732 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr();
3733
3734 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr();
3735 st->print(BULLET"secondary bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap); st->cr();
3736
3737 if (secondary_supers() != nullptr) {
3738 if (Verbose) {
3739 bool is_hashed = (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL);
3740 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length());
3741 for (int i = 0; i < _secondary_supers->length(); i++) {
3742 ResourceMark rm; // for external_name()
3743 Klass* secondary_super = _secondary_supers->at(i);
3744 st->print(BULLET"%2d:", i);
3745 if (is_hashed) {
3746 int home_slot = compute_home_slot(secondary_super, _secondary_supers_bitmap);
3766 print_on_maybe_null(st, BULLET"field type annotations: ", fields_type_annotations());
3767 {
3768 bool have_pv = false;
3769 // previous versions are linked together through the InstanceKlass
3770 for (InstanceKlass* pv_node = previous_versions();
3771 pv_node != nullptr;
3772 pv_node = pv_node->previous_versions()) {
3773 if (!have_pv)
3774 st->print(BULLET"previous version: ");
3775 have_pv = true;
3776 pv_node->constants()->print_value_on(st);
3777 }
3778 if (have_pv) st->cr();
3779 }
3780
3781 print_on_maybe_null(st, BULLET"generic signature: ", generic_signature());
3782 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
3783 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();
3784 print_on_maybe_null(st, BULLET"record components: ", record_components());
3785 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();
3786 if (java_mirror() != nullptr) {
3787 st->print(BULLET"java mirror: ");
3788 java_mirror()->print_value_on(st);
3789 st->cr();
3790 } else {
3791 st->print_cr(BULLET"java mirror: null");
3792 }
3793 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3794 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);
3795 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3796 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_itable(), itable_length(), st);
3797 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3798
3799 FieldPrinter print_static_field(st);
3800 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3801 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3802 FieldPrinter print_nonstatic_field(st);
3803 InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3804 ik->print_nonstatic_fields(&print_nonstatic_field);
3805
3806 st->print(BULLET"non-static oop maps (%d entries): ", nonstatic_oop_map_count());
3807 OopMapBlock* map = start_of_nonstatic_oop_maps();
3808 OopMapBlock* end_map = map + nonstatic_oop_map_count();
3809 while (map < end_map) {
3810 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3811 map++;
3812 }
3813 st->cr();
3814
3815 if (fieldinfo_search_table() != nullptr) {
3816 st->print_cr(BULLET"---- field info search table:");
3817 FieldInfoStream::print_search_table(st, _constants, _fieldinfo_stream, _fieldinfo_search_table);
3818 }
3819 }
3820
3821 void InstanceKlass::print_value_on(outputStream* st) const {
3822 assert(is_klass(), "must be klass");
3823 if (Verbose || WizardMode) access_flags().print_on(st);
3824 name()->print_value_on(st);
3825 }
3826
3827 void FieldPrinter::do_field(fieldDescriptor* fd) {
3828 _st->print(BULLET);
3829 if (_obj == nullptr) {
3830 fd->print_on(_st);
3831 _st->cr();
3832 } else {
3833 fd->print_on_for(_st, _obj);
3834 _st->cr();
3835 }
3836 }
3837
3838
3839 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3840 Klass::oop_print_on(obj, st);
3841
3842 if (this == vmClasses::String_klass()) {
3843 typeArrayOop value = java_lang_String::value(obj);
3844 juint length = java_lang_String::length(obj);
3845 if (value != nullptr &&
3846 value->is_typeArray() &&
3847 length <= (juint) value->length()) {
3848 st->print(BULLET"string: ");
3849 java_lang_String::print(obj, st);
3850 st->cr();
3851 }
3852 }
3853
3854 st->print_cr(BULLET"---- fields (total size %zu words):", oop_size(obj));
3855 FieldPrinter print_field(st, obj);
3856 print_nonstatic_fields(&print_field);
3857
3858 if (this == vmClasses::Class_klass()) {
3859 st->print(BULLET"signature: ");
3860 java_lang_Class::print_signature(obj, st);
3861 st->cr();
3862 Klass* real_klass = java_lang_Class::as_Klass(obj);
3863 if (real_klass != nullptr && real_klass->is_instance_klass()) {
3864 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj));
3865 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3866 }
3867 } else if (this == vmClasses::MethodType_klass()) {
3868 st->print(BULLET"signature: ");
3869 java_lang_invoke_MethodType::print_signature(obj, st);
3870 st->cr();
3871 }
3872 }
3873
3874 #ifndef PRODUCT
3875
|
46 #include "compiler/compileBroker.hpp"
47 #include "gc/shared/collectedHeap.inline.hpp"
48 #include "interpreter/bytecodeStream.hpp"
49 #include "interpreter/oopMapCache.hpp"
50 #include "interpreter/rewriter.hpp"
51 #include "jvm.h"
52 #include "jvmtifiles/jvmti.h"
53 #include "klass.inline.hpp"
54 #include "logging/log.hpp"
55 #include "logging/logMessage.hpp"
56 #include "logging/logStream.hpp"
57 #include "memory/allocation.inline.hpp"
58 #include "memory/iterator.inline.hpp"
59 #include "memory/metadataFactory.hpp"
60 #include "memory/metaspaceClosure.hpp"
61 #include "memory/oopFactory.hpp"
62 #include "memory/resourceArea.hpp"
63 #include "memory/universe.hpp"
64 #include "oops/constantPool.hpp"
65 #include "oops/fieldStreams.inline.hpp"
66 #include "oops/inlineKlass.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/layoutKind.hpp"
74 #include "oops/markWord.hpp"
75 #include "oops/method.hpp"
76 #include "oops/oop.inline.hpp"
77 #include "oops/recordComponent.hpp"
78 #include "oops/refArrayKlass.hpp"
79 #include "oops/symbol.hpp"
80 #include "prims/jvmtiExport.hpp"
81 #include "prims/jvmtiRedefineClasses.hpp"
82 #include "prims/jvmtiThreadState.hpp"
83 #include "prims/methodComparator.hpp"
84 #include "runtime/arguments.hpp"
85 #include "runtime/atomicAccess.hpp"
86 #include "runtime/deoptimization.hpp"
87 #include "runtime/fieldDescriptor.inline.hpp"
88 #include "runtime/handles.inline.hpp"
89 #include "runtime/javaCalls.hpp"
90 #include "runtime/javaThread.inline.hpp"
91 #include "runtime/mutexLocker.hpp"
92 #include "runtime/orderAccess.hpp"
93 #include "runtime/os.inline.hpp"
94 #include "runtime/reflection.hpp"
95 #include "runtime/synchronizer.hpp"
96 #include "runtime/threads.hpp"
97 #include "services/classLoadingService.hpp"
98 #include "services/finalizerService.hpp"
99 #include "services/threadService.hpp"
100 #include "utilities/dtrace.hpp"
101 #include "utilities/events.hpp"
102 #include "utilities/macros.hpp"
103 #include "utilities/nativeStackPrinter.hpp"
104 #include "utilities/ostream.hpp"
105 #include "utilities/stringUtils.hpp"
106 #ifdef COMPILER1
107 #include "c1/c1_Compiler.hpp"
108 #endif
109 #if INCLUDE_JFR
110 #include "jfr/jfrEvents.hpp"
111 #endif
112
113 #ifdef DTRACE_ENABLED
114
115
116 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
117 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
118 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
119 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
120 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
121 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
122 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
123 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
124 #define DTRACE_CLASSINIT_PROBE(type, thread_type) \
137 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait) \
138 { \
139 char* data = nullptr; \
140 int len = 0; \
141 Symbol* clss_name = name(); \
142 if (clss_name != nullptr) { \
143 data = (char*)clss_name->bytes(); \
144 len = clss_name->utf8_length(); \
145 } \
146 HOTSPOT_CLASS_INITIALIZATION_##type( \
147 data, len, (void*)class_loader(), thread_type, wait); \
148 }
149
150 #else // ndef DTRACE_ENABLED
151
152 #define DTRACE_CLASSINIT_PROBE(type, thread_type)
153 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)
154
155 #endif // ndef DTRACE_ENABLED
156
157 void InlineLayoutInfo::metaspace_pointers_do(MetaspaceClosure* it) {
158 log_trace(cds)("Iter(InlineFieldInfo): %p", this);
159 it->push(&_klass);
160 }
161
162 void InlineLayoutInfo::print() const {
163 print_on(tty);
164 }
165
166 void InlineLayoutInfo::print_on(outputStream* st) const {
167 st->print_cr("_klass: " PTR_FORMAT, p2i(_klass));
168 if (_klass != nullptr) {
169 StreamIndentor si(st);
170 _klass->print_on(st);
171 st->cr();
172 }
173
174 st->print("_layout: ");
175 LayoutKindHelper::print_on(_kind, st);
176 st->cr();
177
178 st->print("_null_marker_offset: %d", _null_marker_offset);
179 }
180
181 bool InstanceKlass::_finalization_enabled = true;
182
183 static inline bool is_class_loader(const Symbol* class_name,
184 const ClassFileParser& parser) {
185 assert(class_name != nullptr, "invariant");
186
187 if (class_name == vmSymbols::java_lang_ClassLoader()) {
188 return true;
189 }
190
191 if (vmClasses::ClassLoader_klass_is_loaded()) {
192 const Klass* const super_klass = parser.super_klass();
193 if (super_klass != nullptr) {
194 if (super_klass->is_subtype_of(vmClasses::ClassLoader_klass())) {
195 return true;
196 }
197 }
198 }
199 return false;
200 }
201
202 bool InstanceKlass::field_is_null_free_inline_type(int index) const {
203 return field(index).field_flags().is_null_free_inline_type();
204 }
205
206 bool InstanceKlass::is_class_in_loadable_descriptors_attribute(Symbol* name) const {
207 if (_loadable_descriptors == nullptr) return false;
208 for (int i = 0; i < _loadable_descriptors->length(); i++) {
209 Symbol* class_name = _constants->symbol_at(_loadable_descriptors->at(i));
210 if (class_name == name) return true;
211 }
212 return false;
213 }
214
215 static inline bool is_stack_chunk_class(const Symbol* class_name,
216 const ClassLoaderData* loader_data) {
217 return (class_name == vmSymbols::jdk_internal_vm_StackChunk() &&
218 loader_data->is_the_null_class_loader_data());
219 }
220
221 // private: called to verify that k is a static member of this nest.
222 // We know that k is an instance class in the same package and hence the
223 // same classloader.
224 bool InstanceKlass::has_nest_member(JavaThread* current, InstanceKlass* k) const {
225 assert(!is_hidden(), "unexpected hidden class");
226 if (_nest_members == nullptr || _nest_members == Universe::the_empty_short_array()) {
227 if (log_is_enabled(Trace, class, nestmates)) {
228 ResourceMark rm(current);
229 log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
230 k->external_name(), this->external_name());
231 }
232 return false;
233 }
234
482 log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
483 this->external_name(),
484 access ? "" : "NOT ",
485 k->external_name());
486 return access;
487 }
488
489 const char* InstanceKlass::nest_host_error() {
490 if (_nest_host_index == 0) {
491 return nullptr;
492 } else {
493 constantPoolHandle cph(Thread::current(), constants());
494 return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index);
495 }
496 }
497
498 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
499 const int size = InstanceKlass::size(parser.vtable_size(),
500 parser.itable_size(),
501 nonstatic_oop_map_size(parser.total_oop_map_count()),
502 parser.is_interface(),
503 parser.is_inline_type());
504
505 const Symbol* const class_name = parser.class_name();
506 assert(class_name != nullptr, "invariant");
507 ClassLoaderData* loader_data = parser.loader_data();
508 assert(loader_data != nullptr, "invariant");
509
510 InstanceKlass* ik;
511
512 // Allocation
513 if (parser.is_instance_ref_klass()) {
514 // java.lang.ref.Reference
515 ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
516 } else if (class_name == vmSymbols::java_lang_Class()) {
517 // mirror - java.lang.Class
518 ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
519 } else if (is_stack_chunk_class(class_name, loader_data)) {
520 // stack chunk
521 ik = new (loader_data, size, THREAD) InstanceStackChunkKlass(parser);
522 } else if (is_class_loader(class_name, parser)) {
523 // class loader - java.lang.ClassLoader
524 ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);
525 } else if (parser.is_inline_type()) {
526 // inline type
527 ik = new (loader_data, size, THREAD) InlineKlass(parser);
528 } else {
529 // normal
530 ik = new (loader_data, size, THREAD) InstanceKlass(parser);
531 }
532
533 if (ik != nullptr && UseCompressedClassPointers) {
534 assert(CompressedKlassPointers::is_encodable(ik),
535 "Klass " PTR_FORMAT "needs a narrow Klass ID, but is not encodable", p2i(ik));
536 }
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 MetadataFactory::free_metadata(loader_data, constants());
796 }
797 // Delete any cached resolution errors for the constant pool
798 SystemDictionary::delete_resolution_error(constants());
799
800 set_constants(nullptr);
801 }
802
803 if (inner_classes() != nullptr &&
804 inner_classes() != Universe::the_empty_short_array() &&
805 !inner_classes()->in_aot_cache()) {
806 MetadataFactory::free_array<jushort>(loader_data, inner_classes());
807 }
808 set_inner_classes(nullptr);
809
810 if (nest_members() != nullptr &&
811 nest_members() != Universe::the_empty_short_array() &&
812 !nest_members()->in_aot_cache()) {
813 MetadataFactory::free_array<jushort>(loader_data, nest_members());
814 }
815 set_nest_members(nullptr);
816
817 if (permitted_subclasses() != nullptr &&
818 permitted_subclasses() != Universe::the_empty_short_array() &&
819 !permitted_subclasses()->in_aot_cache()) {
820 MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
821 }
822 set_permitted_subclasses(nullptr);
823
824 if (loadable_descriptors() != nullptr &&
825 loadable_descriptors() != Universe::the_empty_short_array() &&
826 !loadable_descriptors()->in_aot_cache()) {
827 MetadataFactory::free_array<jushort>(loader_data, loadable_descriptors());
828 }
829 set_loadable_descriptors(nullptr);
830
831 if (acmp_maps_array() != nullptr) {
832 MetadataFactory::free_array<int>(loader_data, acmp_maps_array());
833 }
834 set_acmp_maps_array(nullptr);
835
836 // We should deallocate the Annotations instance if it's not in shared spaces.
837 if (annotations() != nullptr && !annotations()->in_aot_cache()) {
838 MetadataFactory::free_metadata(loader_data, annotations());
839 }
840 set_annotations(nullptr);
841
842 SystemDictionaryShared::handle_class_unloading(this);
843
844 #if INCLUDE_CDS_JAVA_HEAP
845 if (CDSConfig::is_dumping_heap()) {
846 HeapShared::remove_scratch_objects(this);
847 }
848 #endif
849 }
850
851 bool InstanceKlass::is_record() const {
852 return _record_components != nullptr &&
853 is_final() &&
854 super() == vmClasses::Record_klass();
855 }
858 return _permitted_subclasses != nullptr &&
859 _permitted_subclasses != Universe::the_empty_short_array();
860 }
861
862 // JLS 8.9: An enum class is either implicitly final and derives
863 // from java.lang.Enum, or else is implicitly sealed to its
864 // anonymous subclasses. This query detects both kinds.
865 // It does not validate the finality or
866 // sealing conditions: it merely checks for a super of Enum.
867 // This is sufficient for recognizing well-formed enums.
868 bool InstanceKlass::is_enum_subclass() const {
869 InstanceKlass* s = super();
870 return (s == vmClasses::Enum_klass() ||
871 (s != nullptr && s->super() == vmClasses::Enum_klass()));
872 }
873
874 bool InstanceKlass::should_be_initialized() const {
875 return !is_initialized();
876 }
877
878 // Static size helper
879 int InstanceKlass::size(int vtable_length,
880 int itable_length,
881 int nonstatic_oop_map_size,
882 bool is_interface,
883 bool is_inline_type) {
884 return align_metadata_size(header_size() +
885 vtable_length +
886 itable_length +
887 nonstatic_oop_map_size +
888 (is_interface ? (int)sizeof(Klass*) / wordSize : 0) +
889 (is_inline_type ? (int)sizeof(InlineKlass::Members) / wordSize : 0));
890 }
891
892 int InstanceKlass::size() const {
893 return size(vtable_length(),
894 itable_length(),
895 nonstatic_oop_map_size(),
896 is_interface(),
897 is_inline_klass());
898 }
899
900 klassItable InstanceKlass::itable() const {
901 return klassItable(const_cast<InstanceKlass*>(this));
902 }
903
904 // JVMTI spec thinks there are signers and protection domain in the
905 // instanceKlass. These accessors pretend these fields are there.
906 // The hprof specification also thinks these fields are in InstanceKlass.
907 oop InstanceKlass::protection_domain() const {
908 // return the protection_domain from the mirror
909 return java_lang_Class::protection_domain(java_mirror());
910 }
911
912 objArrayOop InstanceKlass::signers() const {
913 // return the signers from the mirror
914 return java_lang_Class::signers(java_mirror());
915 }
916
917 oop InstanceKlass::init_lock() const {
918 // return the init lock from the mirror
919 oop lock = java_lang_Class::init_lock(java_mirror());
1032 #ifdef ASSERT
1033 {
1034 Handle h_init_lock(THREAD, init_lock());
1035 ObjectLocker ol(h_init_lock, THREAD);
1036 assert(!is_initialized(), "sanity");
1037 assert(!is_being_initialized(), "sanity");
1038 assert(!is_in_error_state(), "sanity");
1039 }
1040 #endif
1041
1042 set_init_thread(THREAD);
1043 set_initialization_state_and_notify(fully_initialized, CHECK);
1044 }
1045 #endif
1046
1047 bool InstanceKlass::verify_code(TRAPS) {
1048 // 1) Verify the bytecodes
1049 return Verifier::verify(this, should_verify_class(), THREAD);
1050 }
1051
1052 static void load_classes_from_loadable_descriptors_attribute(InstanceKlass *ik, TRAPS) {
1053 if (ik->loadable_descriptors() != Universe::the_empty_short_array() && PreloadClasses) {
1054 ResourceMark rm(THREAD);
1055 HandleMark hm(THREAD);
1056 for (int i = 0; i < ik->loadable_descriptors()->length(); i++) {
1057 Symbol* sig = ik->constants()->symbol_at(ik->loadable_descriptors()->at(i));
1058 if (!Signature::has_envelope(sig)) continue;
1059 TempNewSymbol class_name = Signature::strip_envelope(sig);
1060 if (class_name == ik->name()) continue;
1061 log_info(class, preload)("Preloading of class %s during linking of class %s "
1062 "because of the class is listed in the LoadableDescriptors attribute",
1063 sig->as_C_string(), ik->name()->as_C_string());
1064 oop loader = ik->class_loader();
1065 Klass* klass = SystemDictionary::resolve_or_null(class_name,
1066 Handle(THREAD, loader), THREAD);
1067 if (HAS_PENDING_EXCEPTION) {
1068 CLEAR_PENDING_EXCEPTION;
1069 }
1070 if (klass != nullptr) {
1071 log_info(class, preload)("Preloading of class %s during linking of class %s "
1072 "(cause: LoadableDescriptors attribute) succeeded",
1073 class_name->as_C_string(), ik->name()->as_C_string());
1074 if (!klass->is_inline_klass()) {
1075 // Non value class are allowed by the current spec, but it could be an indication
1076 // of an issue so let's log a warning
1077 log_info(class, preload)("Preloading of class %s during linking of class %s "
1078 "(cause: LoadableDescriptors attribute) but loaded class is not a value class",
1079 class_name->as_C_string(), ik->name()->as_C_string());
1080 }
1081 } else {
1082 log_info(class, preload)("Preloading of class %s during linking of class %s "
1083 "(cause: LoadableDescriptors attribute) failed",
1084 class_name->as_C_string(), ik->name()->as_C_string());
1085 }
1086 }
1087 }
1088 }
1089
1090 void InstanceKlass::link_class(TRAPS) {
1091 assert(is_loaded(), "must be loaded");
1092 if (!is_linked()) {
1093 link_class_impl(CHECK);
1094 }
1095 }
1096
1097 // Called to verify that a class can link during initialization, without
1098 // throwing a VerifyError.
1099 bool InstanceKlass::link_class_or_fail(TRAPS) {
1100 assert(is_loaded(), "must be loaded");
1101 if (!is_linked()) {
1102 link_class_impl(CHECK_false);
1103 }
1104 return is_linked();
1105 }
1106
1107 bool InstanceKlass::link_class_impl(TRAPS) {
1108 if (CDSConfig::is_dumping_static_archive() && SystemDictionaryShared::has_class_failed_verification(this)) {
1109 // This is for CDS static dump only -- we use the in_error_state to indicate that
1140 THREAD_AND_LOCATION,
1141 vmSymbols::java_lang_IncompatibleClassChangeError(),
1142 "class %s has interface %s as super class",
1143 external_name(),
1144 super_klass->external_name()
1145 );
1146 return false;
1147 }
1148
1149 super_klass->link_class_impl(CHECK_false);
1150 }
1151
1152 // link all interfaces implemented by this class before linking this class
1153 Array<InstanceKlass*>* interfaces = local_interfaces();
1154 int num_interfaces = interfaces->length();
1155 for (int index = 0; index < num_interfaces; index++) {
1156 InstanceKlass* interk = interfaces->at(index);
1157 interk->link_class_impl(CHECK_false);
1158 }
1159
1160 if (Arguments::is_valhalla_enabled()) {
1161 // Aggressively preloading all classes from the LoadableDescriptors attribute
1162 // so inline classes can be scalarized in the calling conventions computed below
1163 load_classes_from_loadable_descriptors_attribute(this, THREAD);
1164 assert(!HAS_PENDING_EXCEPTION, "Shouldn't have pending exceptions from call above");
1165 }
1166
1167 // in case the class is linked in the process of linking its superclasses
1168 if (is_linked()) {
1169 return true;
1170 }
1171
1172 // trace only the link time for this klass that includes
1173 // the verification time
1174 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
1175 ClassLoader::perf_class_link_selftime(),
1176 ClassLoader::perf_classes_linked(),
1177 jt->get_thread_stat()->perf_recursion_counts_addr(),
1178 jt->get_thread_stat()->perf_timers_addr(),
1179 PerfClassTraceTime::CLASS_LINK);
1180
1181 // verification & rewriting
1182 {
1183 HandleMark hm(THREAD);
1184 Handle h_init_lock(THREAD, init_lock());
1185 ObjectLocker ol(h_init_lock, CHECK_PREEMPTABLE_false);
1186 // Don't allow preemption if we link/initialize classes below,
1470 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1471 ss.as_string(), cause);
1472 }
1473 } else {
1474
1475 // Step 6
1476 set_init_state(being_initialized);
1477 set_init_thread(jt);
1478 if (debug_logging_enabled) {
1479 ResourceMark rm(jt);
1480 log_debug(class, init)("Thread \"%s\" is initializing %s",
1481 jt->name(), external_name());
1482 }
1483 }
1484 }
1485
1486 // Block preemption once we are the initializer thread. Unmounting now
1487 // would complicate the reentrant case (identity is platform thread).
1488 NoPreemptMark npm(THREAD);
1489
1490 // Pre-allocating an all-zero value to be used to reset nullable flat storages
1491 if (is_inline_klass()) {
1492 InlineKlass* vk = InlineKlass::cast(this);
1493 if (vk->supports_nullable_layouts()) {
1494 oop val = vk->allocate_instance(THREAD);
1495 if (HAS_PENDING_EXCEPTION) {
1496 Handle e(THREAD, PENDING_EXCEPTION);
1497 CLEAR_PENDING_EXCEPTION;
1498 {
1499 EXCEPTION_MARK;
1500 add_initialization_error(THREAD, e);
1501 // Locks object, set state, and notify all waiting threads
1502 set_initialization_state_and_notify(initialization_error, THREAD);
1503 CLEAR_PENDING_EXCEPTION;
1504 }
1505 THROW_OOP(e());
1506 }
1507 vk->set_null_reset_value(val);
1508 }
1509 }
1510
1511 // Step 7
1512 // Next, if C is a class rather than an interface, initialize it's super class and super
1513 // interfaces.
1514 if (!is_interface()) {
1515 Klass* super_klass = super();
1516 if (super_klass != nullptr && super_klass->should_be_initialized()) {
1517 super_klass->initialize(THREAD);
1518 }
1519 // If C implements any interface that declares a non-static, concrete method,
1520 // the initialization of C triggers initialization of its super interfaces.
1521 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1522 // having a superinterface that declares, non-static, concrete methods
1523 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1524 initialize_super_interfaces(THREAD);
1525 }
1526
1527 // If any exceptions, complete abruptly, throwing the same exception as above.
1528 if (HAS_PENDING_EXCEPTION) {
1529 Handle e(THREAD, PENDING_EXCEPTION);
1530 CLEAR_PENDING_EXCEPTION;
1531 {
1532 EXCEPTION_MARK;
1533 add_initialization_error(THREAD, e);
1534 // Locks object, set state, and notify all waiting threads
1535 set_initialization_state_and_notify(initialization_error, THREAD);
1536 CLEAR_PENDING_EXCEPTION;
1537 }
1538 DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1539 THROW_OOP(e());
1540 }
1541 }
1542
1543 // Step 8
1544 {
1545 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1546 if (class_initializer() != nullptr) {
1547 // Timer includes any side effects of class initialization (resolution,
1548 // etc), but not recursive entry into call_class_initializer().
1549 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1550 ClassLoader::perf_class_init_selftime(),
1551 ClassLoader::perf_classes_inited(),
1552 jt->get_thread_stat()->perf_recursion_counts_addr(),
1553 jt->get_thread_stat()->perf_timers_addr(),
1554 PerfClassTraceTime::CLASS_CLINIT);
1555 call_class_initializer(THREAD);
1556 } else {
1557 // The elapsed time is so small it's not worth counting.
1558 if (UsePerfData) {
1559 ClassLoader::perf_classes_inited()->inc();
1560 }
1561 call_class_initializer(THREAD);
1562 }
1563
1564 if (has_strict_static_fields() && !HAS_PENDING_EXCEPTION) {
1565 // Step 9 also verifies that strict static fields have been initialized.
1566 // Status bits were set in ClassFileParser::post_process_parsed_stream.
1567 // After <clinit>, bits must all be clear, or else we must throw an error.
1568 // This is an extremely fast check, so we won't bother with a timer.
1569 assert(fields_status() != nullptr, "");
1570 Symbol* bad_strict_static = nullptr;
1571 for (int index = 0; index < fields_status()->length(); index++) {
1572 // Very fast loop over single byte array looking for a set bit.
1573 if (fields_status()->adr_at(index)->is_strict_static_unset()) {
1574 // This strict static field has not been set by the class initializer.
1575 // Note that in the common no-error case, we read no field metadata.
1576 // We only unpack it when we need to report an error.
1577 FieldInfo fi = field(index);
1578 bad_strict_static = fi.name(constants());
1579 if (debug_logging_enabled) {
1580 ResourceMark rm(jt);
1581 const char* msg = format_strict_static_message(bad_strict_static);
1582 log_debug(class, init)("%s", msg);
1583 } else {
1584 // If we are not logging, do not bother to look for a second offense.
1585 break;
1586 }
1587 }
1588 }
1589 if (bad_strict_static != nullptr) {
1590 throw_strict_static_exception(bad_strict_static, "is unset after initialization of", THREAD);
1591 }
1592 }
1593 }
1594
1595 // Step 9
1596 if (!HAS_PENDING_EXCEPTION) {
1597 set_initialization_state_and_notify(fully_initialized, CHECK);
1598 DEBUG_ONLY(vtable().verify(tty, true);)
1599 CompilationPolicy::replay_training_at_init(this, THREAD);
1600 }
1601 else {
1602 // Step 10 and 11
1603 Handle e(THREAD, PENDING_EXCEPTION);
1604 CLEAR_PENDING_EXCEPTION;
1605 // JVMTI has already reported the pending exception
1606 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1607 JvmtiExport::clear_detected_exception(jt);
1608 {
1609 EXCEPTION_MARK;
1610 add_initialization_error(THREAD, e);
1611 set_initialization_state_and_notify(initialization_error, THREAD);
1612 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1626 }
1627 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1628 }
1629
1630
1631 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1632 Handle h_init_lock(THREAD, init_lock());
1633 if (h_init_lock() != nullptr) {
1634 ObjectLocker ol(h_init_lock, THREAD);
1635 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1636 set_init_state(state);
1637 fence_and_clear_init_lock();
1638 ol.notify_all(CHECK);
1639 } else {
1640 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1641 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1642 set_init_state(state);
1643 }
1644 }
1645
1646 void InstanceKlass::notify_strict_static_access(int field_index, bool is_writing, TRAPS) {
1647 guarantee(field_index >= 0 && field_index < fields_status()->length(), "valid field index");
1648 DEBUG_ONLY(FieldInfo debugfi = field(field_index));
1649 assert(debugfi.access_flags().is_strict(), "");
1650 assert(debugfi.access_flags().is_static(), "");
1651 FieldStatus& fs = *fields_status()->adr_at(field_index);
1652 LogTarget(Trace, class, init) lt;
1653 if (lt.is_enabled()) {
1654 ResourceMark rm(THREAD);
1655 LogStream ls(lt);
1656 FieldInfo fi = field(field_index);
1657 ls.print("notify %s %s %s%s ",
1658 external_name(), is_writing? "Write" : "Read",
1659 fs.is_strict_static_unset() ? "Unset" : "(set)",
1660 fs.is_strict_static_unread() ? "+Unread" : "");
1661 fi.print(&ls, constants());
1662 }
1663 if (fs.is_strict_static_unset()) {
1664 assert(fs.is_strict_static_unread(), "ClassFileParser resp.");
1665 // If it is not set, there are only two reasonable things we can do here:
1666 // - mark it set if this is putstatic
1667 // - throw an error (Read-Before-Write) if this is getstatic
1668
1669 // The unset state is (or should be) transient, and observable only in one
1670 // thread during the execution of <clinit>. Something is wrong here as this
1671 // should not be possible
1672 guarantee(is_reentrant_initialization(THREAD), "unscoped access to strict static");
1673 if (is_writing) {
1674 // clear the "unset" bit, since the field is actually going to be written
1675 fs.update_strict_static_unset(false);
1676 } else {
1677 // throw an IllegalStateException, since we are reading before writing
1678 // see also InstanceKlass::initialize_impl, Step 8 (at end)
1679 Symbol* bad_strict_static = field(field_index).name(constants());
1680 throw_strict_static_exception(bad_strict_static, "is unset before first read in", CHECK);
1681 }
1682 } else {
1683 // Ensure no write after read for final strict statics
1684 FieldInfo fi = field(field_index);
1685 bool is_final = fi.access_flags().is_final();
1686 if (is_final) {
1687 // no final write after read, so observing a constant freezes it, as if <clinit> ended early
1688 // (maybe we could trust the constant a little earlier, before <clinit> ends)
1689 if (is_writing && !fs.is_strict_static_unread()) {
1690 Symbol* bad_strict_static = fi.name(constants());
1691 throw_strict_static_exception(bad_strict_static, "is set after read (as final) in", CHECK);
1692 } else if (!is_writing && fs.is_strict_static_unread()) {
1693 fs.update_strict_static_unread(false);
1694 }
1695 }
1696 }
1697 }
1698
1699 void InstanceKlass::throw_strict_static_exception(Symbol* field_name, const char* when, TRAPS) {
1700 ResourceMark rm(THREAD);
1701 const char* msg = format_strict_static_message(field_name, when);
1702 THROW_MSG(vmSymbols::java_lang_IllegalStateException(), msg);
1703 }
1704
1705 const char* InstanceKlass::format_strict_static_message(Symbol* field_name, const char* when) {
1706 stringStream ss;
1707 ss.print("Strict static \"%s\" %s %s",
1708 field_name->as_C_string(),
1709 when == nullptr ? "is unset in" : when,
1710 external_name());
1711 return ss.as_string();
1712 }
1713
1714 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1715 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1716 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1717 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1718
1719 DeoptimizationScope deopt_scope;
1720 {
1721 MutexLocker ml(current, Compile_lock);
1722
1723 set_init_state(InstanceKlass::loaded);
1724 // make sure init_state store is already done.
1725 // The compiler reads the hierarchy outside of the Compile_lock.
1726 // Access ordering is used to add to hierarchy.
1727
1728 // Link into hierarchy.
1729 append_to_sibling_list(); // add to superklass/sibling list
1730 process_interfaces(); // handle all "implements" declarations
1731
1732 // Now mark all code that depended on old class hierarchy.
1733 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1944 : vmSymbols::java_lang_IllegalAccessException(), external_name());
1945 }
1946 }
1947
1948 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
1949 // Need load-acquire for lock-free read
1950 if (array_klasses_acquire() == nullptr) {
1951
1952 // Recursively lock array allocation
1953 RecursiveLocker rl(MultiArray_lock, THREAD);
1954
1955 // Check if another thread created the array klass while we were waiting for the lock.
1956 if (array_klasses() == nullptr) {
1957 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
1958 // use 'release' to pair with lock-free load
1959 release_set_array_klasses(k);
1960 }
1961 }
1962
1963 // array_klasses() will always be set at this point
1964 ArrayKlass* ak = array_klasses();
1965 assert(ak != nullptr, "should be set");
1966 return ak->array_klass(n, THREAD);
1967 }
1968
1969 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1970 // Need load-acquire for lock-free read
1971 ArrayKlass* ak = array_klasses_acquire();
1972 if (ak == nullptr) {
1973 return nullptr;
1974 } else {
1975 return ak->array_klass_or_null(n);
1976 }
1977 }
1978
1979 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1980 return array_klass(1, THREAD);
1981 }
1982
1983 ArrayKlass* InstanceKlass::array_klass_or_null() {
1984 return array_klass_or_null(1);
1985 }
1986
1987 static int call_class_initializer_counter = 0; // for debugging
1988
1989 Method* InstanceKlass::class_initializer() const {
1990 Method* clinit = find_method(
1991 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1992 if (clinit != nullptr && clinit->is_class_initializer()) {
1993 return clinit;
1994 }
1995 return nullptr;
1996 }
1997
1998 void InstanceKlass::call_class_initializer(TRAPS) {
1999 if (ReplayCompiles &&
2000 (ReplaySuppressInitializers == 1 ||
2001 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
2002 // Hide the existence of the initializer for the purpose of replaying the compile
2003 return;
2004 }
2005
2006 #if INCLUDE_CDS
2007 // This is needed to ensure the consistency of the archived heap objects.
2008 if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
2009 AOTClassInitializer::call_runtime_setup(THREAD, this);
2010 return;
2011 } else if (has_archived_enum_objs()) {
2012 assert(in_aot_cache(), "must be");
2081
2082 void InstanceKlass::mask_for(const methodHandle& method, int bci,
2083 InterpreterOopMap* entry_for) {
2084 // Lazily create the _oop_map_cache at first request.
2085 // Load_acquire is needed to safely get instance published with CAS by another thread.
2086 OopMapCache* oop_map_cache = AtomicAccess::load_acquire(&_oop_map_cache);
2087 if (oop_map_cache == nullptr) {
2088 // Try to install new instance atomically.
2089 oop_map_cache = new OopMapCache();
2090 OopMapCache* other = AtomicAccess::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
2091 if (other != nullptr) {
2092 // Someone else managed to install before us, ditch local copy and use the existing one.
2093 delete oop_map_cache;
2094 oop_map_cache = other;
2095 }
2096 }
2097 // _oop_map_cache is constant after init; lookup below does its own locking.
2098 oop_map_cache->lookup(method, bci, entry_for);
2099 }
2100
2101
2102 FieldInfo InstanceKlass::field(int index) const {
2103 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2104 if (fs.index() == index) {
2105 return fs.to_FieldInfo();
2106 }
2107 }
2108 fatal("Field not found");
2109 return FieldInfo();
2110 }
2111
2112 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
2113 JavaFieldStream fs(this);
2114 if (fs.lookup(name, sig)) {
2115 assert(fs.name() == name, "name must match");
2116 assert(fs.signature() == sig, "signature must match");
2117 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2118 return true;
2119 }
2120 return false;
2161
2162 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
2163 // search order according to newest JVM spec (5.4.3.2, p.167).
2164 // 1) search for field in current klass
2165 if (find_local_field(name, sig, fd)) {
2166 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
2167 }
2168 // 2) search for field recursively in direct superinterfaces
2169 if (is_static) {
2170 Klass* intf = find_interface_field(name, sig, fd);
2171 if (intf != nullptr) return intf;
2172 }
2173 // 3) apply field lookup recursively if superclass exists
2174 { InstanceKlass* supr = super();
2175 if (supr != nullptr) return supr->find_field(name, sig, is_static, fd);
2176 }
2177 // 4) otherwise field lookup fails
2178 return nullptr;
2179 }
2180
2181 bool InstanceKlass::contains_field_offset(int offset) {
2182 if (this->is_inline_klass()) {
2183 InlineKlass* vk = InlineKlass::cast(this);
2184 return offset >= vk->payload_offset() && offset < (vk->payload_offset() + vk->payload_size_in_bytes());
2185 } else {
2186 fieldDescriptor fd;
2187 return find_field_from_offset(offset, false, &fd);
2188 }
2189 }
2190
2191 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2192 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2193 if (fs.offset() == offset) {
2194 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2195 if (fd->is_static() == is_static) return true;
2196 }
2197 }
2198 return false;
2199 }
2200
2201 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2202 const InstanceKlass* klass = this;
2203 while (klass != nullptr) {
2204 if (klass->find_local_field_from_offset(offset, is_static, fd)) {
2205 return true;
2206 }
2207 klass = klass->super();
2208 }
2209 return false;
2210 }
2211
2212 bool InstanceKlass::find_local_flat_field_containing_offset(int offset, fieldDescriptor* fd) const {
2213 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2214 if (!fs.is_flat()) {
2215 continue;
2216 }
2217
2218 if (fs.offset() > offset) {
2219 continue;
2220 }
2221
2222 const int offset_in_flat_field = offset - fs.offset();
2223 const InlineLayoutInfo layout_info = inline_layout_info(fs.index());
2224 const int field_size = layout_info.klass()->layout_size_in_bytes(layout_info.kind());
2225
2226 assert(LayoutKindHelper::is_flat(layout_info.kind()), "Must be flat");
2227
2228 if (offset_in_flat_field < field_size) {
2229 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2230 assert(!fd->is_static(), "Static fields are not flattened");
2231
2232 return true;
2233 }
2234 }
2235
2236 return false;
2237 }
2238
2239 bool InstanceKlass::find_flat_field_containing_offset(int offset, fieldDescriptor* fd) const {
2240 const InstanceKlass* klass = this;
2241 while (klass != nullptr) {
2242 if (klass->find_local_flat_field_containing_offset(offset, fd)) {
2243 return true;
2244 }
2245
2246 klass = klass->super();
2247 }
2248
2249 return false;
2250 }
2251
2252 void InstanceKlass::methods_do(void f(Method* method)) {
2253 // Methods aren't stable until they are loaded. This can be read outside
2254 // a lock through the ClassLoaderData for profiling
2255 // Redefined scratch classes are on the list and need to be cleaned
2256 if (!is_loaded() && !is_scratch_class()) {
2257 return;
2258 }
2259
2260 int len = methods()->length();
2261 for (int index = 0; index < len; index++) {
2262 Method* m = methods()->at(index);
2263 assert(m->is_method(), "must be method");
2264 f(m);
2265 }
2266 }
2267
2268
2269 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
2270 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2271 if (fs.access_flags().is_static()) {
2272 fieldDescriptor& fd = fs.field_descriptor();
2273 cl->do_field(&fd);
2274 }
2275 }
2276 }
2277
2278
2279 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
2280 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2281 if (fs.access_flags().is_static()) {
2282 fieldDescriptor& fd = fs.field_descriptor();
2283 f(&fd, mirror, CHECK);
2284 }
2285 }
2286 }
2287
2288 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
2289 InstanceKlass* super = this->super();
2290 if (super != nullptr) {
2291 super->do_nonstatic_fields(cl);
2292 }
2293 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2294 fieldDescriptor& fd = fs.field_descriptor();
2295 if (!fd.is_static()) {
2296 cl->do_field(&fd);
2297 }
2298 }
2299 }
2300
2591 }
2592
2593 // uncached_lookup_method searches both the local class methods array and all
2594 // superclasses methods arrays, skipping any overpass methods in superclasses,
2595 // and possibly skipping private methods.
2596 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2597 const Symbol* signature,
2598 OverpassLookupMode overpass_mode,
2599 PrivateLookupMode private_mode) const {
2600 OverpassLookupMode overpass_local_mode = overpass_mode;
2601 const InstanceKlass* klass = this;
2602 while (klass != nullptr) {
2603 Method* const method = klass->find_method_impl(name,
2604 signature,
2605 overpass_local_mode,
2606 StaticLookupMode::find,
2607 private_mode);
2608 if (method != nullptr) {
2609 return method;
2610 }
2611 if (name == vmSymbols::object_initializer_name()) {
2612 break; // <init> is never inherited
2613 }
2614 klass = klass->super();
2615 overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses
2616 }
2617 return nullptr;
2618 }
2619
2620 #ifdef ASSERT
2621 // search through class hierarchy and return true if this class or
2622 // one of the superclasses was redefined
2623 bool InstanceKlass::has_redefined_this_or_super() const {
2624 const InstanceKlass* klass = this;
2625 while (klass != nullptr) {
2626 if (klass->has_been_redefined()) {
2627 return true;
2628 }
2629 klass = klass->super();
2630 }
2631 return false;
2632 }
2633 #endif
3006 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
3007
3008 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
3009 / itableOffsetEntry::size();
3010
3011 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
3012 if (ioe->interface_klass() != nullptr) {
3013 it->push(ioe->interface_klass_addr());
3014 itableMethodEntry* ime = ioe->first_method_entry(this);
3015 int n = klassItable::method_count_for_interface(ioe->interface_klass());
3016 for (int index = 0; index < n; index ++) {
3017 it->push(ime[index].method_addr());
3018 }
3019 }
3020 }
3021 }
3022
3023 it->push(&_nest_host);
3024 it->push(&_nest_members);
3025 it->push(&_permitted_subclasses);
3026 it->push(&_loadable_descriptors);
3027 it->push(&_acmp_maps_array, MetaspaceClosure::_writable);
3028 it->push(&_record_components);
3029 it->push(&_inline_layout_info_array, MetaspaceClosure::_writable);
3030
3031 if (CDSConfig::is_dumping_full_module_graph() && !defined_by_other_loaders()) {
3032 it->push(&_package_entry);
3033 }
3034 }
3035
3036 #if INCLUDE_CDS
3037 void InstanceKlass::remove_unshareable_info() {
3038
3039 if (is_linked()) {
3040 assert(can_be_verified_at_dumptime(), "must be");
3041 // Remember this so we can avoid walking the hierarchy at runtime.
3042 set_verified_at_dump_time();
3043 }
3044
3045 _misc_flags.set_has_init_deps_processed(false);
3046
3047 Klass::remove_unshareable_info();
3048
3049 if (SystemDictionaryShared::has_class_failed_verification(this)) {
3061
3062 { // Otherwise this needs to take out the Compile_lock.
3063 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
3064 init_implementor();
3065 }
3066
3067 // Call remove_unshareable_info() on other objects that belong to this class, except
3068 // for constants()->remove_unshareable_info(), which is called in a separate pass in
3069 // ArchiveBuilder::make_klasses_shareable(),
3070
3071 for (int i = 0; i < methods()->length(); i++) {
3072 Method* m = methods()->at(i);
3073 m->remove_unshareable_info();
3074 }
3075
3076 // do array classes also.
3077 if (array_klasses() != nullptr) {
3078 array_klasses()->remove_unshareable_info();
3079 }
3080
3081 // These are not allocated from metaspace. They are safe to set to nullptr.
3082 _source_debug_extension = nullptr;
3083 _dep_context = nullptr;
3084 _osr_nmethods_head = nullptr;
3085 #if INCLUDE_JVMTI
3086 _breakpoints = nullptr;
3087 _previous_versions = nullptr;
3088 _cached_class_file = nullptr;
3089 _jvmti_cached_class_field_map = nullptr;
3090 #endif
3091
3092 _init_thread = nullptr;
3093 _methods_jmethod_ids = nullptr;
3094 _jni_ids = nullptr;
3095 _oop_map_cache = nullptr;
3096 if (CDSConfig::is_dumping_method_handles() && HeapShared::is_lambda_proxy_klass(this)) {
3097 // keep _nest_host
3098 } else {
3099 // clear _nest_host to ensure re-load at runtime
3100 _nest_host = nullptr;
3101 }
3137 void InstanceKlass::compute_has_loops_flag_for_methods() {
3138 Array<Method*>* methods = this->methods();
3139 for (int index = 0; index < methods->length(); ++index) {
3140 Method* m = methods->at(index);
3141 if (!m->is_overpass()) { // work around JDK-8305771
3142 m->compute_has_loops_flag();
3143 }
3144 }
3145 }
3146
3147 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
3148 PackageEntry* pkg_entry, TRAPS) {
3149 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
3150 // before the InstanceKlass is added to the SystemDictionary. Make
3151 // sure the current state is <loaded.
3152 assert(!is_loaded(), "invalid init state");
3153 assert(!shared_loading_failed(), "Must not try to load failed class again");
3154 set_package(loader_data, pkg_entry, CHECK);
3155 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
3156
3157 if (is_inline_klass()) {
3158 InlineKlass::cast(this)->initialize_calling_convention(CHECK);
3159 }
3160
3161 Array<Method*>* methods = this->methods();
3162 int num_methods = methods->length();
3163 for (int index = 0; index < num_methods; ++index) {
3164 methods->at(index)->restore_unshareable_info(CHECK);
3165 }
3166 #if INCLUDE_JVMTI
3167 if (JvmtiExport::has_redefined_a_class()) {
3168 // Reinitialize vtable because RedefineClasses may have changed some
3169 // entries in this vtable for super classes so the CDS vtable might
3170 // point to old or obsolete entries. RedefineClasses doesn't fix up
3171 // vtables in the shared system dictionary, only the main one.
3172 // It also redefines the itable too so fix that too.
3173 // First fix any default methods that point to a super class that may
3174 // have been redefined.
3175 bool trace_name_printed = false;
3176 adjust_default_methods(&trace_name_printed);
3177 if (verified_at_dump_time()) {
3178 // Initialize vtable and itable for classes which can be verified at dump time.
3179 // Unlinked classes such as old classes with major version < 50 cannot be verified
3180 // at dump time.
3181 vtable().initialize_vtable();
3182 itable().initialize_itable();
3183 }
3184 }
3185 #endif // INCLUDE_JVMTI
3186
3187 // restore constant pool resolved references
3188 constants()->restore_unshareable_info(CHECK);
3189
3190 // Restore acmp_maps java array from the version stored in metadata.
3191 // if it cannot be found in the archive
3192 if (Arguments::is_valhalla_enabled() && has_acmp_maps_offset() && java_mirror()->obj_field(_acmp_maps_offset) == nullptr) {
3193 int acmp_maps_size = _acmp_maps_array->length();
3194 typeArrayOop map = oopFactory::new_intArray(acmp_maps_size, CHECK);
3195 typeArrayHandle map_h(THREAD, map);
3196 for (int i = 0; i < acmp_maps_size; i++) {
3197 map_h->int_at_put(i, _acmp_maps_array->at(i));
3198 }
3199 java_mirror()->obj_field_put(_acmp_maps_offset, map_h());
3200 }
3201
3202 if (array_klasses() != nullptr) {
3203 // To get a consistent list of classes we need MultiArray_lock to ensure
3204 // array classes aren't observed while they are being restored.
3205 RecursiveLocker rl(MultiArray_lock, THREAD);
3206 assert(this == ObjArrayKlass::cast(array_klasses())->bottom_klass(), "sanity");
3207 // Array classes have null protection domain.
3208 // --> see ArrayKlass::complete_create_array_klass()
3209 if (class_loader_data() == nullptr) {
3210 ResourceMark rm(THREAD);
3211 log_debug(cds)(" loader_data %s ", loader_data == nullptr ? "nullptr" : "non null");
3212 log_debug(cds)(" this %s array_klasses %s ", this->name()->as_C_string(), array_klasses()->name()->as_C_string());
3213 }
3214 assert(!array_klasses()->is_refined_objArray_klass(), "must be non-refined objarrayklass");
3215 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
3216 }
3217
3218 // Initialize @ValueBased class annotation if not already set in the archived klass.
3219 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
3220 set_is_value_based();
3221 }
3222
3223 DEBUG_ONLY(FieldInfoStream::validate_search_table(_constants, _fieldinfo_stream, _fieldinfo_search_table));
3224 }
3225
3226 bool InstanceKlass::can_be_verified_at_dumptime() const {
3227 if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(this)) {
3228 // This is a class that was dumped into the base archive, so we know
3229 // it was verified at dump time.
3230 return true;
3231 }
3232
3233 if (CDSConfig::is_preserving_verification_constraints()) {
3234 return true;
3350 constants()->release_C_heap_structures();
3351 }
3352 }
3353
3354 // The constant pool is on stack if any of the methods are executing or
3355 // referenced by handles.
3356 bool InstanceKlass::on_stack() const {
3357 return _constants->on_stack();
3358 }
3359
3360 Symbol* InstanceKlass::source_file_name() const { return _constants->source_file_name(); }
3361 u2 InstanceKlass::source_file_name_index() const { return _constants->source_file_name_index(); }
3362 void InstanceKlass::set_source_file_name_index(u2 sourcefile_index) { _constants->set_source_file_name_index(sourcefile_index); }
3363
3364 // minor and major version numbers of class file
3365 u2 InstanceKlass::minor_version() const { return _constants->minor_version(); }
3366 void InstanceKlass::set_minor_version(u2 minor_version) { _constants->set_minor_version(minor_version); }
3367 u2 InstanceKlass::major_version() const { return _constants->major_version(); }
3368 void InstanceKlass::set_major_version(u2 major_version) { _constants->set_major_version(major_version); }
3369
3370 bool InstanceKlass::supports_inline_types() const {
3371 return major_version() >= Verifier::VALUE_TYPES_MAJOR_VERSION && minor_version() == Verifier::JAVA_PREVIEW_MINOR_VERSION;
3372 }
3373
3374 const InstanceKlass* InstanceKlass::get_klass_version(int version) const {
3375 for (const InstanceKlass* ik = this; ik != nullptr; ik = ik->previous_versions()) {
3376 if (ik->constants()->version() == version) {
3377 return ik;
3378 }
3379 }
3380 return nullptr;
3381 }
3382
3383 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
3384 if (array == nullptr) {
3385 _source_debug_extension = nullptr;
3386 } else {
3387 // Adding one to the attribute length in order to store a null terminator
3388 // character could cause an overflow because the attribute length is
3389 // already coded with an u4 in the classfile, but in practice, it's
3390 // unlikely to happen.
3391 assert((length+1) > length, "Overflow checking");
3392 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
3393 for (int i = 0; i < length; i++) {
3394 sde[i] = array[i];
3395 }
3396 sde[length] = '\0';
3397 _source_debug_extension = sde;
3398 }
3399 }
3400
3401 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); }
3402 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); }
3403 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); }
3404
3405 const char* InstanceKlass::signature_name() const {
3406 return signature_name_of_carrier(JVM_SIGNATURE_CLASS);
3407 }
3408
3409 const char* InstanceKlass::signature_name_of_carrier(char c) const {
3410 // Get the internal name as a c string
3411 const char* src = (const char*) (name()->as_C_string());
3412 const int src_length = (int)strlen(src);
3413
3414 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
3415
3416 // Add L or Q as type indicator
3417 int dest_index = 0;
3418 dest[dest_index++] = c;
3419
3420 // Add the actual class name
3421 for (int src_index = 0; src_index < src_length; ) {
3422 dest[dest_index++] = src[src_index++];
3423 }
3424
3425 if (is_hidden()) { // Replace the last '+' with a '.'.
3426 for (int index = (int)src_length; index > 0; index--) {
3427 if (dest[index] == '+') {
3428 dest[index] = JVM_SIGNATURE_DOT;
3429 break;
3430 }
3431 }
3432 }
3433
3434 // Add the semicolon and the null
3435 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3436 dest[dest_index] = '\0';
3437 return dest;
3438 }
3679 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3680 constantPoolHandle i_cp(THREAD, constants());
3681 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3682 int ioff = iter.inner_class_info_index();
3683 if (ioff != 0) {
3684 // Check to see if the name matches the class we're looking for
3685 // before attempting to find the class.
3686 if (i_cp->klass_name_at_matches(this, ioff)) {
3687 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3688 if (this == inner_klass) {
3689 *ooff = iter.outer_class_info_index();
3690 *noff = iter.inner_name_index();
3691 return true;
3692 }
3693 }
3694 }
3695 }
3696 return false;
3697 }
3698
3699 void InstanceKlass::check_can_be_annotated_with_NullRestricted(InstanceKlass* type, Symbol* container_klass_name, TRAPS) {
3700 assert(type->is_instance_klass(), "Sanity check");
3701 if (type->is_identity_class()) {
3702 ResourceMark rm(THREAD);
3703 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
3704 err_msg("Class %s expects class %s to be a value class, but it is an identity class",
3705 container_klass_name->as_C_string(),
3706 type->external_name()));
3707 }
3708
3709 if (type->is_abstract()) {
3710 ResourceMark rm(THREAD);
3711 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
3712 err_msg("Class %s expects class %s to be concrete value type, but it is an abstract class",
3713 container_klass_name->as_C_string(),
3714 type->external_name()));
3715 }
3716 }
3717
3718 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3719 InstanceKlass* outer_klass = nullptr;
3720 *inner_is_member = false;
3721 int ooff = 0, noff = 0;
3722 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3723 if (has_inner_classes_attr) {
3724 constantPoolHandle i_cp(THREAD, constants());
3725 if (ooff != 0) {
3726 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3727 if (!ok->is_instance_klass()) {
3728 // If the outer class is not an instance klass then it cannot have
3729 // declared any inner classes.
3730 ResourceMark rm(THREAD);
3731 // Names are all known to be < 64k so we know this formatted message is not excessively large.
3732 Exceptions::fthrow(
3733 THREAD_AND_LOCATION,
3734 vmSymbols::java_lang_IncompatibleClassChangeError(),
3735 "%s and %s disagree on InnerClasses attribute",
3736 ok->external_name(),
3737 external_name());
3764 u2 InstanceKlass::compute_modifier_flags() const {
3765 u2 access = access_flags().as_unsigned_short();
3766
3767 // But check if it happens to be member class.
3768 InnerClassesIterator iter(this);
3769 for (; !iter.done(); iter.next()) {
3770 int ioff = iter.inner_class_info_index();
3771 // Inner class attribute can be zero, skip it.
3772 // Strange but true: JVM spec. allows null inner class refs.
3773 if (ioff == 0) continue;
3774
3775 // only look at classes that are already loaded
3776 // since we are looking for the flags for our self.
3777 Symbol* inner_name = constants()->klass_name_at(ioff);
3778 if (name() == inner_name) {
3779 // This is really a member class.
3780 access = iter.inner_access_flags();
3781 break;
3782 }
3783 }
3784 if (!Arguments::is_valhalla_enabled()) {
3785 // Remember to strip ACC_SUPER bit without Valhalla
3786 access &= (~JVM_ACC_SUPER);
3787 }
3788 return access;
3789 }
3790
3791 jint InstanceKlass::jvmti_class_status() const {
3792 jint result = 0;
3793
3794 if (is_linked()) {
3795 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3796 }
3797
3798 if (is_initialized()) {
3799 assert(is_linked(), "Class status is not consistent");
3800 result |= JVMTI_CLASS_STATUS_INITIALIZED;
3801 }
3802 if (is_in_error_state()) {
3803 result |= JVMTI_CLASS_STATUS_ERROR;
3804 }
3805 return result;
3806 }
3807
3808 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
4022 }
4023 osr = osr->osr_link();
4024 }
4025
4026 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
4027 if (best != nullptr && best->comp_level() >= comp_level) {
4028 return best;
4029 }
4030 return nullptr;
4031 }
4032
4033 // -----------------------------------------------------------------------------------------------------
4034 // Printing
4035
4036 #define BULLET " - "
4037
4038 static const char* state_names[] = {
4039 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
4040 };
4041
4042 static void print_vtable(address self, intptr_t* start, int len, outputStream* st) {
4043 ResourceMark rm;
4044 int* forward_refs = NEW_RESOURCE_ARRAY(int, len);
4045 for (int i = 0; i < len; i++) forward_refs[i] = 0;
4046 for (int i = 0; i < len; i++) {
4047 intptr_t e = start[i];
4048 st->print("%d : " INTPTR_FORMAT, i, e);
4049 if (forward_refs[i] != 0) {
4050 int from = forward_refs[i];
4051 int off = (int) start[from];
4052 st->print(" (offset %d <= [%d])", off, from);
4053 }
4054 if (MetaspaceObj::is_valid((Metadata*)e)) {
4055 st->print(" ");
4056 ((Metadata*)e)->print_value_on(st);
4057 } else if (self != nullptr && e > 0 && e < 0x10000) {
4058 address location = self + e;
4059 int index = (int)((intptr_t*)location - start);
4060 st->print(" (offset %d => [%d])", (int)e, index);
4061 if (index >= 0 && index < len)
4062 forward_refs[index] = i;
4063 }
4064 st->cr();
4065 }
4066 }
4067
4068 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
4069 return print_vtable(nullptr, reinterpret_cast<intptr_t*>(start), len, st);
4070 }
4071
4072 const char* InstanceKlass::init_state_name() const {
4073 return state_names[init_state()];
4074 }
4075
4076 void InstanceKlass::print_on(outputStream* st) const {
4077 assert(is_klass(), "must be klass");
4078 Klass::print_on(st);
4079
4080 st->print(BULLET"instance size: %d", size_helper()); st->cr();
4081 st->print(BULLET"klass size: %d", size()); st->cr();
4082 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
4083 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
4084 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
4085 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
4086 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
4087 st->print(BULLET"sub: ");
4088 Klass* sub = subklass();
4089 int n;
4090 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
4091 if (n < MaxSubklassPrintSize) {
4092 sub->print_value_on(st);
4093 st->print(" ");
4094 }
4095 }
4096 if (n >= MaxSubklassPrintSize) st->print("(%zd more klasses...)", n - MaxSubklassPrintSize);
4097 st->cr();
4098
4099 if (is_interface()) {
4100 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
4101 if (nof_implementors() == 1) {
4102 st->print_cr(BULLET"implementor: ");
4103 st->print(" ");
4104 implementor()->print_value_on(st);
4105 st->cr();
4106 }
4107 }
4108
4109
4110 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
4111 st->print(BULLET"methods: ");
4112 print_array_on(st, methods(), [](outputStream* ost, Method* method) {
4113 method->print_value_on(ost);
4114 });
4115 st->print(BULLET"method ordering: ");
4116 print_array_on(st, method_ordering(), [](outputStream* ost, int i) {
4117 ost->print("%d", i);
4118 });
4119 if (default_methods() != nullptr) {
4120 st->print(BULLET"default_methods: ");
4121 print_array_on(st, default_methods(), [](outputStream* ost, Method* method) {
4122 method->print_value_on(ost);
4123 });
4124 }
4125 print_on_maybe_null(st, BULLET"default vtable indices: ", default_vtable_indices());
4126 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
4127 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
4128
4129 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr();
4130
4131 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr();
4132 st->print(BULLET"secondary bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap); st->cr();
4133
4134 if (secondary_supers() != nullptr) {
4135 if (Verbose) {
4136 bool is_hashed = (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL);
4137 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length());
4138 for (int i = 0; i < _secondary_supers->length(); i++) {
4139 ResourceMark rm; // for external_name()
4140 Klass* secondary_super = _secondary_supers->at(i);
4141 st->print(BULLET"%2d:", i);
4142 if (is_hashed) {
4143 int home_slot = compute_home_slot(secondary_super, _secondary_supers_bitmap);
4163 print_on_maybe_null(st, BULLET"field type annotations: ", fields_type_annotations());
4164 {
4165 bool have_pv = false;
4166 // previous versions are linked together through the InstanceKlass
4167 for (InstanceKlass* pv_node = previous_versions();
4168 pv_node != nullptr;
4169 pv_node = pv_node->previous_versions()) {
4170 if (!have_pv)
4171 st->print(BULLET"previous version: ");
4172 have_pv = true;
4173 pv_node->constants()->print_value_on(st);
4174 }
4175 if (have_pv) st->cr();
4176 }
4177
4178 print_on_maybe_null(st, BULLET"generic signature: ", generic_signature());
4179 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
4180 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();
4181 print_on_maybe_null(st, BULLET"record components: ", record_components());
4182 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();
4183 st->print(BULLET"loadable descriptors: "); loadable_descriptors()->print_value_on(st); st->cr();
4184 if (java_mirror() != nullptr) {
4185 st->print(BULLET"java mirror: ");
4186 java_mirror()->print_value_on(st);
4187 st->cr();
4188 } else {
4189 st->print_cr(BULLET"java mirror: null");
4190 }
4191 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
4192 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);
4193 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
4194 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(nullptr, start_of_itable(), itable_length(), st);
4195
4196 InstanceKlass* ik = const_cast<InstanceKlass*>(this);
4197 // There is no oop so static and nonstatic printing can use the same printer.
4198 FieldPrinter field_printer(st);
4199 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
4200 ik->do_local_static_fields(&field_printer);
4201 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
4202 ik->print_nonstatic_fields(&field_printer);
4203
4204 st->print(BULLET"non-static oop maps (%d entries): ", nonstatic_oop_map_count());
4205 OopMapBlock* map = start_of_nonstatic_oop_maps();
4206 OopMapBlock* end_map = map + nonstatic_oop_map_count();
4207 while (map < end_map) {
4208 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
4209 map++;
4210 }
4211 st->cr();
4212
4213 if (fieldinfo_search_table() != nullptr) {
4214 st->print_cr(BULLET"---- field info search table:");
4215 FieldInfoStream::print_search_table(st, _constants, _fieldinfo_stream, _fieldinfo_search_table);
4216 }
4217 }
4218
4219 void InstanceKlass::print_value_on(outputStream* st) const {
4220 assert(is_klass(), "must be klass");
4221 if (Verbose || WizardMode) access_flags().print_on(st);
4222 name()->print_value_on(st);
4223 }
4224
4225 void FieldPrinter::do_field(fieldDescriptor* fd) {
4226 for (int i = 0; i < _indent; i++) _st->print(" ");
4227 _st->print(BULLET);
4228 // Handles the cases of static fields or instance fields but no oop is given.
4229 if (_obj == nullptr) {
4230 fd->print_on(_st, _base_offset);
4231 _st->cr();
4232 } else {
4233 fd->print_on_for(_st, _obj, _indent, _base_offset);
4234 if (!fd->field_flags().is_flat()) _st->cr();
4235 }
4236 }
4237
4238
4239 void InstanceKlass::oop_print_on(oop obj, outputStream* st, int indent, int base_offset) {
4240 Klass::oop_print_on(obj, st);
4241
4242 if (this == vmClasses::String_klass()) {
4243 typeArrayOop value = java_lang_String::value(obj);
4244 juint length = java_lang_String::length(obj);
4245 if (value != nullptr &&
4246 value->is_typeArray() &&
4247 length <= (juint) value->length()) {
4248 st->print(BULLET"string: ");
4249 java_lang_String::print(obj, st);
4250 st->cr();
4251 }
4252 }
4253
4254 st->print_cr(BULLET"---- fields (total size %zu words):", oop_size(obj));
4255 FieldPrinter print_field(st, obj, indent, base_offset);
4256 print_nonstatic_fields(&print_field);
4257
4258 if (this == vmClasses::Class_klass()) {
4259 st->print(BULLET"signature: ");
4260 java_lang_Class::print_signature(obj, st);
4261 st->cr();
4262 Klass* real_klass = java_lang_Class::as_Klass(obj);
4263 if (real_klass != nullptr && real_klass->is_instance_klass()) {
4264 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj));
4265 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
4266 }
4267 } else if (this == vmClasses::MethodType_klass()) {
4268 st->print(BULLET"signature: ");
4269 java_lang_invoke_MethodType::print_signature(obj, st);
4270 st->cr();
4271 }
4272 }
4273
4274 #ifndef PRODUCT
4275
|