1 /*
2 * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
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"
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 }
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
2698 #if INCLUDE_CDS
2699 void InstanceKlass::remove_unshareable_info() {
2700
2701 if (is_linked()) {
2702 assert(can_be_verified_at_dumptime(), "must be");
2703 // Remember this so we can avoid walking the hierarchy at runtime.
2704 set_verified_at_dump_time();
2705 }
2706
2707 _misc_flags.set_has_init_deps_processed(false);
2708
2709 Klass::remove_unshareable_info();
2710
2711 if (SystemDictionaryShared::has_class_failed_verification(this)) {
2712 // Classes are attempted to link during dumping and may fail,
2713 // but these classes are still in the dictionary and class list in CLD.
2714 // If the class has failed verification, there is nothing else to remove.
2715 return;
2723
2724 { // Otherwise this needs to take out the Compile_lock.
2725 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2726 init_implementor();
2727 }
2728
2729 // Call remove_unshareable_info() on other objects that belong to this class, except
2730 // for constants()->remove_unshareable_info(), which is called in a separate pass in
2731 // ArchiveBuilder::make_klasses_shareable(),
2732
2733 for (int i = 0; i < methods()->length(); i++) {
2734 Method* m = methods()->at(i);
2735 m->remove_unshareable_info();
2736 }
2737
2738 // do array classes also.
2739 if (array_klasses() != nullptr) {
2740 array_klasses()->remove_unshareable_info();
2741 }
2742
2743 // These are not allocated from metaspace. They are safe to set to null.
2744 _source_debug_extension = nullptr;
2745 _dep_context = nullptr;
2746 _osr_nmethods_head = nullptr;
2747 #if INCLUDE_JVMTI
2748 _breakpoints = nullptr;
2749 _previous_versions = nullptr;
2750 _cached_class_file = nullptr;
2751 _jvmti_cached_class_field_map = nullptr;
2752 #endif
2753
2754 _init_thread = nullptr;
2755 _methods_jmethod_ids = nullptr;
2756 _jni_ids = nullptr;
2757 _oop_map_cache = nullptr;
2758 if (CDSConfig::is_dumping_method_handles() && HeapShared::is_lambda_proxy_klass(this)) {
2759 // keep _nest_host
2760 } else {
2761 // clear _nest_host to ensure re-load at runtime
2762 _nest_host = nullptr;
2763 }
2814 void InstanceKlass::compute_has_loops_flag_for_methods() {
2815 Array<Method*>* methods = this->methods();
2816 for (int index = 0; index < methods->length(); ++index) {
2817 Method* m = methods->at(index);
2818 if (!m->is_overpass()) { // work around JDK-8305771
2819 m->compute_has_loops_flag();
2820 }
2821 }
2822 }
2823
2824 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
2825 PackageEntry* pkg_entry, TRAPS) {
2826 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
2827 // before the InstanceKlass is added to the SystemDictionary. Make
2828 // sure the current state is <loaded.
2829 assert(!is_loaded(), "invalid init state");
2830 assert(!shared_loading_failed(), "Must not try to load failed class again");
2831 set_package(loader_data, pkg_entry, CHECK);
2832 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2833
2834 Array<Method*>* methods = this->methods();
2835 int num_methods = methods->length();
2836 for (int index = 0; index < num_methods; ++index) {
2837 methods->at(index)->restore_unshareable_info(CHECK);
2838 }
2839 #if INCLUDE_JVMTI
2840 if (JvmtiExport::has_redefined_a_class()) {
2841 // Reinitialize vtable because RedefineClasses may have changed some
2842 // entries in this vtable for super classes so the CDS vtable might
2843 // point to old or obsolete entries. RedefineClasses doesn't fix up
2844 // vtables in the shared system dictionary, only the main one.
2845 // It also redefines the itable too so fix that too.
2846 // First fix any default methods that point to a super class that may
2847 // have been redefined.
2848 bool trace_name_printed = false;
2849 adjust_default_methods(&trace_name_printed);
2850 if (verified_at_dump_time()) {
2851 // Initialize vtable and itable for classes which can be verified at dump time.
2852 // Unlinked classes such as old classes with major version < 50 cannot be verified
2853 // at dump time.
2854 vtable().initialize_vtable();
2855 itable().initialize_itable();
2856 }
2857 }
2858 #endif // INCLUDE_JVMTI
2859
2860 // restore constant pool resolved references
2861 constants()->restore_unshareable_info(CHECK);
2862
2863 if (array_klasses() != nullptr) {
2864 // To get a consistent list of classes we need MultiArray_lock to ensure
2865 // array classes aren't observed while they are being restored.
2866 RecursiveLocker rl(MultiArray_lock, THREAD);
2867 assert(this == array_klasses()->bottom_klass(), "sanity");
2868 // Array classes have null protection domain.
2869 // --> see ArrayKlass::complete_create_array_klass()
2870 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
2871 }
2872
2873 // Initialize @ValueBased class annotation if not already set in the archived klass.
2874 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
2875 set_is_value_based();
2876 }
2877
2878 DEBUG_ONLY(FieldInfoStream::validate_search_table(_constants, _fieldinfo_stream, _fieldinfo_search_table));
2879 }
2880
2881 bool InstanceKlass::can_be_verified_at_dumptime() const {
2882 if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(this)) {
2883 // This is a class that was dumped into the base archive, so we know
2884 // it was verified at dump time.
2885 return true;
2886 }
2887
2888 if (CDSConfig::is_preserving_verification_constraints()) {
2889 return true;
3005 constants()->release_C_heap_structures();
3006 }
3007 }
3008
3009 // The constant pool is on stack if any of the methods are executing or
3010 // referenced by handles.
3011 bool InstanceKlass::on_stack() const {
3012 return _constants->on_stack();
3013 }
3014
3015 Symbol* InstanceKlass::source_file_name() const { return _constants->source_file_name(); }
3016 u2 InstanceKlass::source_file_name_index() const { return _constants->source_file_name_index(); }
3017 void InstanceKlass::set_source_file_name_index(u2 sourcefile_index) { _constants->set_source_file_name_index(sourcefile_index); }
3018
3019 // minor and major version numbers of class file
3020 u2 InstanceKlass::minor_version() const { return _constants->minor_version(); }
3021 void InstanceKlass::set_minor_version(u2 minor_version) { _constants->set_minor_version(minor_version); }
3022 u2 InstanceKlass::major_version() const { return _constants->major_version(); }
3023 void InstanceKlass::set_major_version(u2 major_version) { _constants->set_major_version(major_version); }
3024
3025 const InstanceKlass* InstanceKlass::get_klass_version(int version) const {
3026 for (const InstanceKlass* ik = this; ik != nullptr; ik = ik->previous_versions()) {
3027 if (ik->constants()->version() == version) {
3028 return ik;
3029 }
3030 }
3031 return nullptr;
3032 }
3033
3034 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
3035 if (array == nullptr) {
3036 _source_debug_extension = nullptr;
3037 } else {
3038 // Adding one to the attribute length in order to store a null terminator
3039 // character could cause an overflow because the attribute length is
3040 // already coded with an u4 in the classfile, but in practice, it's
3041 // unlikely to happen.
3042 assert((length+1) > length, "Overflow checking");
3043 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
3044 for (int i = 0; i < length; i++) {
3045 sde[i] = array[i];
3046 }
3047 sde[length] = '\0';
3048 _source_debug_extension = sde;
3049 }
3050 }
3051
3052 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); }
3053 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); }
3054 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); }
3055
3056 const char* InstanceKlass::signature_name() const {
3057
3058 // Get the internal name as a c string
3059 const char* src = (const char*) (name()->as_C_string());
3060 const int src_length = (int)strlen(src);
3061
3062 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
3063
3064 // Add L as type indicator
3065 int dest_index = 0;
3066 dest[dest_index++] = JVM_SIGNATURE_CLASS;
3067
3068 // Add the actual class name
3069 for (int src_index = 0; src_index < src_length; ) {
3070 dest[dest_index++] = src[src_index++];
3071 }
3072
3073 if (is_hidden()) { // Replace the last '+' with a '.'.
3074 for (int index = (int)src_length; index > 0; index--) {
3075 if (dest[index] == '+') {
3076 dest[index] = JVM_SIGNATURE_DOT;
3077 break;
3078 }
3079 }
3080 }
3081
3082 // Add the semicolon and the null
3083 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3084 dest[dest_index] = '\0';
3085 return dest;
3086 }
3327 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3328 constantPoolHandle i_cp(THREAD, constants());
3329 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3330 int ioff = iter.inner_class_info_index();
3331 if (ioff != 0) {
3332 // Check to see if the name matches the class we're looking for
3333 // before attempting to find the class.
3334 if (i_cp->klass_name_at_matches(this, ioff)) {
3335 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3336 if (this == inner_klass) {
3337 *ooff = iter.outer_class_info_index();
3338 *noff = iter.inner_name_index();
3339 return true;
3340 }
3341 }
3342 }
3343 }
3344 return false;
3345 }
3346
3347 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3348 InstanceKlass* outer_klass = nullptr;
3349 *inner_is_member = false;
3350 int ooff = 0, noff = 0;
3351 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3352 if (has_inner_classes_attr) {
3353 constantPoolHandle i_cp(THREAD, constants());
3354 if (ooff != 0) {
3355 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3356 if (!ok->is_instance_klass()) {
3357 // If the outer class is not an instance klass then it cannot have
3358 // declared any inner classes.
3359 ResourceMark rm(THREAD);
3360 // Names are all known to be < 64k so we know this formatted message is not excessively large.
3361 Exceptions::fthrow(
3362 THREAD_AND_LOCATION,
3363 vmSymbols::java_lang_IncompatibleClassChangeError(),
3364 "%s and %s disagree on InnerClasses attribute",
3365 ok->external_name(),
3366 external_name());
3393 u2 InstanceKlass::compute_modifier_flags() const {
3394 u2 access = access_flags().as_unsigned_short();
3395
3396 // But check if it happens to be member class.
3397 InnerClassesIterator iter(this);
3398 for (; !iter.done(); iter.next()) {
3399 int ioff = iter.inner_class_info_index();
3400 // Inner class attribute can be zero, skip it.
3401 // Strange but true: JVM spec. allows null inner class refs.
3402 if (ioff == 0) continue;
3403
3404 // only look at classes that are already loaded
3405 // since we are looking for the flags for our self.
3406 Symbol* inner_name = constants()->klass_name_at(ioff);
3407 if (name() == inner_name) {
3408 // This is really a member class.
3409 access = iter.inner_access_flags();
3410 break;
3411 }
3412 }
3413 // Remember to strip ACC_SUPER bit
3414 return (access & (~JVM_ACC_SUPER));
3415 }
3416
3417 jint InstanceKlass::jvmti_class_status() const {
3418 jint result = 0;
3419
3420 if (is_linked()) {
3421 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3422 }
3423
3424 if (is_initialized()) {
3425 assert(is_linked(), "Class status is not consistent");
3426 result |= JVMTI_CLASS_STATUS_INITIALIZED;
3427 }
3428 if (is_in_error_state()) {
3429 result |= JVMTI_CLASS_STATUS_ERROR;
3430 }
3431 return result;
3432 }
3433
3434 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
3648 }
3649 osr = osr->osr_link();
3650 }
3651
3652 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
3653 if (best != nullptr && best->comp_level() >= comp_level) {
3654 return best;
3655 }
3656 return nullptr;
3657 }
3658
3659 // -----------------------------------------------------------------------------------------------------
3660 // Printing
3661
3662 #define BULLET " - "
3663
3664 static const char* state_names[] = {
3665 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3666 };
3667
3668 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3669 for (int i = 0; i < len; i++) {
3670 intptr_t e = start[i];
3671 st->print("%d : " INTPTR_FORMAT, i, e);
3672 if (MetaspaceObj::is_valid((Metadata*)e)) {
3673 st->print(" ");
3674 ((Metadata*)e)->print_value_on(st);
3675 }
3676 st->cr();
3677 }
3678 }
3679
3680 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3681 return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3682 }
3683
3684 const char* InstanceKlass::init_state_name() const {
3685 return state_names[init_state()];
3686 }
3687
3688 void InstanceKlass::print_on(outputStream* st) const {
3689 assert(is_klass(), "must be klass");
3690 Klass::print_on(st);
3691
3692 st->print(BULLET"instance size: %d", size_helper()); st->cr();
3693 st->print(BULLET"klass size: %d", size()); st->cr();
3694 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
3695 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
3696 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
3697 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
3698 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3699 st->print(BULLET"sub: ");
3700 Klass* sub = subklass();
3701 int n;
3702 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3703 if (n < MaxSubklassPrintSize) {
3704 sub->print_value_on(st);
3705 st->print(" ");
3706 }
3707 }
3708 if (n >= MaxSubklassPrintSize) st->print("(%zd more klasses...)", n - MaxSubklassPrintSize);
3709 st->cr();
3710
3711 if (is_interface()) {
3712 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
3713 if (nof_implementors() == 1) {
3714 st->print_cr(BULLET"implementor: ");
3715 st->print(" ");
3716 implementor()->print_value_on(st);
3717 st->cr();
3718 }
3719 }
3720
3721 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3722 st->print(BULLET"methods: "); methods()->print_value_on(st); st->cr();
3723 if (Verbose || WizardMode) {
3724 Array<Method*>* method_array = methods();
3725 for (int i = 0; i < method_array->length(); i++) {
3726 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3727 }
3728 }
3729 st->print(BULLET"method ordering: "); method_ordering()->print_value_on(st); st->cr();
3730 if (default_methods() != nullptr) {
3731 st->print(BULLET"default_methods: "); default_methods()->print_value_on(st); st->cr();
3732 if (Verbose) {
3733 Array<Method*>* method_array = default_methods();
3734 for (int i = 0; i < method_array->length(); i++) {
3735 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3736 }
3737 }
3738 }
3739 print_on_maybe_null(st, BULLET"default vtable indices: ", default_vtable_indices());
3740 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
3741 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3742
3743 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr();
3744
3745 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr();
3746 st->print(BULLET"secondary bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap); st->cr();
3747
3748 if (secondary_supers() != nullptr) {
3749 if (Verbose) {
3750 bool is_hashed = (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL);
3751 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length());
3752 for (int i = 0; i < _secondary_supers->length(); i++) {
3753 ResourceMark rm; // for external_name()
3754 Klass* secondary_super = _secondary_supers->at(i);
3755 st->print(BULLET"%2d:", i);
3756 if (is_hashed) {
3757 int home_slot = compute_home_slot(secondary_super, _secondary_supers_bitmap);
3777 print_on_maybe_null(st, BULLET"field type annotations: ", fields_type_annotations());
3778 {
3779 bool have_pv = false;
3780 // previous versions are linked together through the InstanceKlass
3781 for (InstanceKlass* pv_node = previous_versions();
3782 pv_node != nullptr;
3783 pv_node = pv_node->previous_versions()) {
3784 if (!have_pv)
3785 st->print(BULLET"previous version: ");
3786 have_pv = true;
3787 pv_node->constants()->print_value_on(st);
3788 }
3789 if (have_pv) st->cr();
3790 }
3791
3792 print_on_maybe_null(st, BULLET"generic signature: ", generic_signature());
3793 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
3794 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();
3795 print_on_maybe_null(st, BULLET"record components: ", record_components());
3796 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();
3797 if (java_mirror() != nullptr) {
3798 st->print(BULLET"java mirror: ");
3799 java_mirror()->print_value_on(st);
3800 st->cr();
3801 } else {
3802 st->print_cr(BULLET"java mirror: null");
3803 }
3804 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3805 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);
3806 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3807 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_itable(), itable_length(), st);
3808 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3809
3810 FieldPrinter print_static_field(st);
3811 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3812 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3813 FieldPrinter print_nonstatic_field(st);
3814 InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3815 ik->print_nonstatic_fields(&print_nonstatic_field);
3816
3817 st->print(BULLET"non-static oop maps (%d entries): ", nonstatic_oop_map_count());
3818 OopMapBlock* map = start_of_nonstatic_oop_maps();
3819 OopMapBlock* end_map = map + nonstatic_oop_map_count();
3820 while (map < end_map) {
3821 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3822 map++;
3823 }
3824 st->cr();
3825
3826 if (fieldinfo_search_table() != nullptr) {
3827 st->print_cr(BULLET"---- field info search table:");
3828 FieldInfoStream::print_search_table(st, _constants, _fieldinfo_stream, _fieldinfo_search_table);
3829 }
3830 }
3831
3832 void InstanceKlass::print_value_on(outputStream* st) const {
3833 assert(is_klass(), "must be klass");
3834 if (Verbose || WizardMode) access_flags().print_on(st);
3835 name()->print_value_on(st);
3836 }
3837
3838 void FieldPrinter::do_field(fieldDescriptor* fd) {
3839 _st->print(BULLET);
3840 if (_obj == nullptr) {
3841 fd->print_on(_st);
3842 _st->cr();
3843 } else {
3844 fd->print_on_for(_st, _obj);
3845 _st->cr();
3846 }
3847 }
3848
3849
3850 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3851 Klass::oop_print_on(obj, st);
3852
3853 if (this == vmClasses::String_klass()) {
3854 typeArrayOop value = java_lang_String::value(obj);
3855 juint length = java_lang_String::length(obj);
3856 if (value != nullptr &&
3857 value->is_typeArray() &&
3858 length <= (juint) value->length()) {
3859 st->print(BULLET"string: ");
3860 java_lang_String::print(obj, st);
3861 st->cr();
3862 }
3863 }
3864
3865 st->print_cr(BULLET"---- fields (total size %zu words):", oop_size(obj));
3866 FieldPrinter print_field(st, obj);
3867 print_nonstatic_fields(&print_field);
3868
3869 if (this == vmClasses::Class_klass()) {
3870 st->print(BULLET"signature: ");
3871 java_lang_Class::print_signature(obj, st);
3872 st->cr();
3873 Klass* real_klass = java_lang_Class::as_Klass(obj);
3874 if (real_klass != nullptr && real_klass->is_instance_klass()) {
3875 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj));
3876 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3877 }
3878 } else if (this == vmClasses::MethodType_klass()) {
3879 st->print(BULLET"signature: ");
3880 java_lang_invoke_MethodType::print_signature(obj, st);
3881 st->cr();
3882 }
3883 }
3884
3885 #ifndef PRODUCT
3886
|
1 /*
2 * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
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/markWord.hpp"
74 #include "oops/method.hpp"
75 #include "oops/oop.inline.hpp"
76 #include "oops/recordComponent.hpp"
77 #include "oops/refArrayKlass.hpp"
78 #include "oops/symbol.hpp"
79 #include "prims/jvmtiExport.hpp"
80 #include "prims/jvmtiRedefineClasses.hpp"
81 #include "prims/jvmtiThreadState.hpp"
82 #include "prims/methodComparator.hpp"
83 #include "runtime/arguments.hpp"
84 #include "runtime/atomicAccess.hpp"
85 #include "runtime/deoptimization.hpp"
86 #include "runtime/fieldDescriptor.inline.hpp"
87 #include "runtime/handles.inline.hpp"
88 #include "runtime/javaCalls.hpp"
89 #include "runtime/javaThread.inline.hpp"
90 #include "runtime/mutexLocker.hpp"
91 #include "runtime/orderAccess.hpp"
92 #include "runtime/os.inline.hpp"
93 #include "runtime/reflection.hpp"
94 #include "runtime/synchronizer.hpp"
95 #include "runtime/threads.hpp"
96 #include "services/classLoadingService.hpp"
97 #include "services/finalizerService.hpp"
135 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait) \
136 { \
137 char* data = nullptr; \
138 int len = 0; \
139 Symbol* clss_name = name(); \
140 if (clss_name != nullptr) { \
141 data = (char*)clss_name->bytes(); \
142 len = clss_name->utf8_length(); \
143 } \
144 HOTSPOT_CLASS_INITIALIZATION_##type( \
145 data, len, (void*)class_loader(), thread_type, wait); \
146 }
147
148 #else // ndef DTRACE_ENABLED
149
150 #define DTRACE_CLASSINIT_PROBE(type, thread_type)
151 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)
152
153 #endif // ndef DTRACE_ENABLED
154
155 void InlineLayoutInfo::metaspace_pointers_do(MetaspaceClosure* it) {
156 log_trace(cds)("Iter(InlineFieldInfo): %p", this);
157 it->push(&_klass);
158 }
159
160 bool InstanceKlass::_finalization_enabled = true;
161
162 static inline bool is_class_loader(const Symbol* class_name,
163 const ClassFileParser& parser) {
164 assert(class_name != nullptr, "invariant");
165
166 if (class_name == vmSymbols::java_lang_ClassLoader()) {
167 return true;
168 }
169
170 if (vmClasses::ClassLoader_klass_is_loaded()) {
171 const Klass* const super_klass = parser.super_klass();
172 if (super_klass != nullptr) {
173 if (super_klass->is_subtype_of(vmClasses::ClassLoader_klass())) {
174 return true;
175 }
176 }
177 }
178 return false;
179 }
180
181 bool InstanceKlass::field_is_null_free_inline_type(int index) const {
182 return field(index).field_flags().is_null_free_inline_type();
183 }
184
185 bool InstanceKlass::is_class_in_loadable_descriptors_attribute(Symbol* name) const {
186 if (_loadable_descriptors == nullptr) return false;
187 for (int i = 0; i < _loadable_descriptors->length(); i++) {
188 Symbol* class_name = _constants->symbol_at(_loadable_descriptors->at(i));
189 if (class_name == name) return true;
190 }
191 return false;
192 }
193
194 static inline bool is_stack_chunk_class(const Symbol* class_name,
195 const ClassLoaderData* loader_data) {
196 return (class_name == vmSymbols::jdk_internal_vm_StackChunk() &&
197 loader_data->is_the_null_class_loader_data());
198 }
199
200 // private: called to verify that k is a static member of this nest.
201 // We know that k is an instance class in the same package and hence the
202 // same classloader.
203 bool InstanceKlass::has_nest_member(JavaThread* current, InstanceKlass* k) const {
204 assert(!is_hidden(), "unexpected hidden class");
205 if (_nest_members == nullptr || _nest_members == Universe::the_empty_short_array()) {
206 if (log_is_enabled(Trace, class, nestmates)) {
207 ResourceMark rm(current);
208 log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
209 k->external_name(), this->external_name());
210 }
211 return false;
212 }
213
461 log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
462 this->external_name(),
463 access ? "" : "NOT ",
464 k->external_name());
465 return access;
466 }
467
468 const char* InstanceKlass::nest_host_error() {
469 if (_nest_host_index == 0) {
470 return nullptr;
471 } else {
472 constantPoolHandle cph(Thread::current(), constants());
473 return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index);
474 }
475 }
476
477 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
478 const int size = InstanceKlass::size(parser.vtable_size(),
479 parser.itable_size(),
480 nonstatic_oop_map_size(parser.total_oop_map_count()),
481 parser.is_interface(),
482 parser.is_inline_type());
483
484 const Symbol* const class_name = parser.class_name();
485 assert(class_name != nullptr, "invariant");
486 ClassLoaderData* loader_data = parser.loader_data();
487 assert(loader_data != nullptr, "invariant");
488
489 InstanceKlass* ik;
490
491 // Allocation
492 if (parser.is_instance_ref_klass()) {
493 // java.lang.ref.Reference
494 ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
495 } else if (class_name == vmSymbols::java_lang_Class()) {
496 // mirror - java.lang.Class
497 ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
498 } else if (is_stack_chunk_class(class_name, loader_data)) {
499 // stack chunk
500 ik = new (loader_data, size, THREAD) InstanceStackChunkKlass(parser);
501 } else if (is_class_loader(class_name, parser)) {
502 // class loader - java.lang.ClassLoader
503 ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);
504 } else if (parser.is_inline_type()) {
505 // inline type
506 ik = new (loader_data, size, THREAD) InlineKlass(parser);
507 } else {
508 // normal
509 ik = new (loader_data, size, THREAD) InstanceKlass(parser);
510 }
511
512 if (ik != nullptr && UseCompressedClassPointers) {
513 assert(CompressedKlassPointers::is_encodable(ik),
514 "Klass " PTR_FORMAT "needs a narrow Klass ID, but is not encodable", p2i(ik));
515 }
516
517 // Check for pending exception before adding to the loader data and incrementing
518 // class count. Can get OOM here.
519 if (HAS_PENDING_EXCEPTION) {
520 return nullptr;
521 }
522
523 #ifdef ASSERT
524 ik->bounds_check((address) ik->start_of_vtable(), false, size);
525 ik->bounds_check((address) ik->start_of_itable(), false, size);
526 ik->bounds_check((address) ik->end_of_itable(), true, size);
527 ik->bounds_check((address) ik->end_of_nonstatic_oop_maps(), true, size);
528 #endif //ASSERT
529 return ik;
530 }
531
532 #ifndef PRODUCT
533 bool InstanceKlass::bounds_check(address addr, bool edge_ok, intptr_t size_in_bytes) const {
534 const char* bad = nullptr;
535 address end = nullptr;
536 if (addr < (address)this) {
537 bad = "before";
538 } else if (addr == (address)this) {
539 if (edge_ok) return true;
540 bad = "just before";
541 } else if (addr == (end = (address)this + sizeof(intptr_t) * (size_in_bytes < 0 ? size() : size_in_bytes))) {
542 if (edge_ok) return true;
543 bad = "just after";
544 } else if (addr > end) {
545 bad = "after";
546 } else {
547 return true;
548 }
549 tty->print_cr("%s object bounds: " INTPTR_FORMAT " [" INTPTR_FORMAT ".." INTPTR_FORMAT "]",
550 bad, (intptr_t)addr, (intptr_t)this, (intptr_t)end);
551 Verbose = WizardMode = true; this->print(); //@@
552 return false;
553 }
554 #endif //PRODUCT
555
556 // copy method ordering from resource area to Metaspace
557 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
558 if (m != nullptr) {
559 // allocate a new array and copy contents (memcpy?)
560 _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
561 for (int i = 0; i < m->length(); i++) {
562 _method_ordering->at_put(i, m->at(i));
563 }
564 } else {
565 _method_ordering = Universe::the_empty_int_array();
566 }
567 }
568
569 // create a new array of vtable_indices for default methods
570 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
571 Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
572 assert(default_vtable_indices() == nullptr, "only create once");
573 set_default_vtable_indices(vtable_indices);
574 return vtable_indices;
575 }
576
577
578 InstanceKlass::InstanceKlass() {
579 assert(CDSConfig::is_dumping_static_archive() || CDSConfig::is_using_archive(), "only for CDS");
580 }
581
582 InstanceKlass::InstanceKlass(const ClassFileParser& parser, KlassKind kind, markWord prototype_header, ReferenceType reference_type) :
583 Klass(kind, prototype_header),
584 _nest_members(nullptr),
585 _nest_host(nullptr),
586 _permitted_subclasses(nullptr),
587 _record_components(nullptr),
588 _static_field_size(parser.static_field_size()),
589 _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
590 _itable_len(parser.itable_size()),
591 _nest_host_index(0),
592 _init_state(allocated),
593 _reference_type(reference_type),
594 _acmp_maps_offset(0),
595 _init_thread(nullptr),
596 _inline_layout_info_array(nullptr),
597 _loadable_descriptors(nullptr),
598 _acmp_maps_array(nullptr),
599 _adr_inline_klass_members(nullptr)
600 {
601 set_vtable_length(parser.vtable_size());
602 set_access_flags(parser.access_flags());
603 if (parser.is_hidden()) set_is_hidden();
604 set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
605 false));
606 if (parser.has_inlined_fields()) {
607 set_has_inlined_fields();
608 }
609
610 assert(nullptr == _methods, "underlying memory not zeroed?");
611 assert(is_instance_klass(), "is layout incorrect?");
612 assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
613 }
614
615 void InstanceKlass::set_is_cloneable() {
616 if (name() == vmSymbols::java_lang_invoke_MemberName()) {
617 assert(is_final(), "no subclasses allowed");
618 // MemberName cloning should not be intrinsified and always happen in JVM_Clone.
619 } else if (reference_type() != REF_NONE) {
620 // Reference cloning should not be intrinsified and always happen in JVM_Clone.
621 } else {
622 set_is_cloneable_fast();
623 }
624 }
625
626 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
627 Array<Method*>* methods) {
628 if (methods != nullptr && methods != Universe::the_empty_method_array() &&
744
745 deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
746 set_transitive_interfaces(nullptr);
747 set_local_interfaces(nullptr);
748
749 if (fieldinfo_stream() != nullptr && !fieldinfo_stream()->in_aot_cache()) {
750 MetadataFactory::free_array<u1>(loader_data, fieldinfo_stream());
751 }
752 set_fieldinfo_stream(nullptr);
753
754 if (fieldinfo_search_table() != nullptr && !fieldinfo_search_table()->in_aot_cache()) {
755 MetadataFactory::free_array<u1>(loader_data, fieldinfo_search_table());
756 }
757 set_fieldinfo_search_table(nullptr);
758
759 if (fields_status() != nullptr && !fields_status()->in_aot_cache()) {
760 MetadataFactory::free_array<FieldStatus>(loader_data, fields_status());
761 }
762 set_fields_status(nullptr);
763
764 if (inline_layout_info_array() != nullptr) {
765 MetadataFactory::free_array<InlineLayoutInfo>(loader_data, inline_layout_info_array());
766 }
767 set_inline_layout_info_array(nullptr);
768
769 // If a method from a redefined class is using this constant pool, don't
770 // delete it, yet. The new class's previous version will point to this.
771 if (constants() != nullptr) {
772 assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
773 if (!constants()->in_aot_cache()) {
774 MetadataFactory::free_metadata(loader_data, constants());
775 }
776 // Delete any cached resolution errors for the constant pool
777 SystemDictionary::delete_resolution_error(constants());
778
779 set_constants(nullptr);
780 }
781
782 if (inner_classes() != nullptr &&
783 inner_classes() != Universe::the_empty_short_array() &&
784 !inner_classes()->in_aot_cache()) {
785 MetadataFactory::free_array<jushort>(loader_data, inner_classes());
786 }
787 set_inner_classes(nullptr);
788
789 if (nest_members() != nullptr &&
790 nest_members() != Universe::the_empty_short_array() &&
791 !nest_members()->in_aot_cache()) {
792 MetadataFactory::free_array<jushort>(loader_data, nest_members());
793 }
794 set_nest_members(nullptr);
795
796 if (permitted_subclasses() != nullptr &&
797 permitted_subclasses() != Universe::the_empty_short_array() &&
798 !permitted_subclasses()->in_aot_cache()) {
799 MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
800 }
801 set_permitted_subclasses(nullptr);
802
803 if (loadable_descriptors() != nullptr &&
804 loadable_descriptors() != Universe::the_empty_short_array() &&
805 !loadable_descriptors()->in_aot_cache()) {
806 MetadataFactory::free_array<jushort>(loader_data, loadable_descriptors());
807 }
808 set_loadable_descriptors(nullptr);
809
810 if (acmp_maps_array() != nullptr) {
811 MetadataFactory::free_array<int>(loader_data, acmp_maps_array());
812 }
813 set_acmp_maps_array(nullptr);
814
815 // We should deallocate the Annotations instance if it's not in shared spaces.
816 if (annotations() != nullptr && !annotations()->in_aot_cache()) {
817 MetadataFactory::free_metadata(loader_data, annotations());
818 }
819 set_annotations(nullptr);
820
821 SystemDictionaryShared::handle_class_unloading(this);
822
823 #if INCLUDE_CDS_JAVA_HEAP
824 if (CDSConfig::is_dumping_heap()) {
825 HeapShared::remove_scratch_objects(this);
826 }
827 #endif
828 }
829
830 bool InstanceKlass::is_record() const {
831 return _record_components != nullptr &&
832 is_final() &&
833 super() == vmClasses::Record_klass();
834 }
837 return _permitted_subclasses != nullptr &&
838 _permitted_subclasses != Universe::the_empty_short_array();
839 }
840
841 // JLS 8.9: An enum class is either implicitly final and derives
842 // from java.lang.Enum, or else is implicitly sealed to its
843 // anonymous subclasses. This query detects both kinds.
844 // It does not validate the finality or
845 // sealing conditions: it merely checks for a super of Enum.
846 // This is sufficient for recognizing well-formed enums.
847 bool InstanceKlass::is_enum_subclass() const {
848 InstanceKlass* s = super();
849 return (s == vmClasses::Enum_klass() ||
850 (s != nullptr && s->super() == vmClasses::Enum_klass()));
851 }
852
853 bool InstanceKlass::should_be_initialized() const {
854 return !is_initialized();
855 }
856
857 // Static size helper
858 int InstanceKlass::size(int vtable_length,
859 int itable_length,
860 int nonstatic_oop_map_size,
861 bool is_interface,
862 bool is_inline_type) {
863 return align_metadata_size(header_size() +
864 vtable_length +
865 itable_length +
866 nonstatic_oop_map_size +
867 (is_interface ? (int)sizeof(Klass*) / wordSize : 0) +
868 (is_inline_type ? (int)sizeof(InlineKlass::Members) / wordSize : 0));
869 }
870
871 int InstanceKlass::size() const {
872 return size(vtable_length(),
873 itable_length(),
874 nonstatic_oop_map_size(),
875 is_interface(),
876 is_inline_klass());
877 }
878
879 klassItable InstanceKlass::itable() const {
880 return klassItable(const_cast<InstanceKlass*>(this));
881 }
882
883 // JVMTI spec thinks there are signers and protection domain in the
884 // instanceKlass. These accessors pretend these fields are there.
885 // The hprof specification also thinks these fields are in InstanceKlass.
886 oop InstanceKlass::protection_domain() const {
887 // return the protection_domain from the mirror
888 return java_lang_Class::protection_domain(java_mirror());
889 }
890
891 objArrayOop InstanceKlass::signers() const {
892 // return the signers from the mirror
893 return java_lang_Class::signers(java_mirror());
894 }
895
896 oop InstanceKlass::init_lock() const {
897 // return the init lock from the mirror
898 oop lock = java_lang_Class::init_lock(java_mirror());
1011 #ifdef ASSERT
1012 {
1013 Handle h_init_lock(THREAD, init_lock());
1014 ObjectLocker ol(h_init_lock, THREAD);
1015 assert(!is_initialized(), "sanity");
1016 assert(!is_being_initialized(), "sanity");
1017 assert(!is_in_error_state(), "sanity");
1018 }
1019 #endif
1020
1021 set_init_thread(THREAD);
1022 set_initialization_state_and_notify(fully_initialized, CHECK);
1023 }
1024 #endif
1025
1026 bool InstanceKlass::verify_code(TRAPS) {
1027 // 1) Verify the bytecodes
1028 return Verifier::verify(this, should_verify_class(), THREAD);
1029 }
1030
1031 static void load_classes_from_loadable_descriptors_attribute(InstanceKlass *ik, TRAPS) {
1032 ResourceMark rm(THREAD);
1033 if (ik->loadable_descriptors() != nullptr && PreloadClasses) {
1034 HandleMark hm(THREAD);
1035 for (int i = 0; i < ik->loadable_descriptors()->length(); i++) {
1036 Symbol* sig = ik->constants()->symbol_at(ik->loadable_descriptors()->at(i));
1037 if (!Signature::has_envelope(sig)) continue;
1038 TempNewSymbol class_name = Signature::strip_envelope(sig);
1039 if (class_name == ik->name()) continue;
1040 log_info(class, preload)("Preloading of class %s during linking of class %s "
1041 "because of the class is listed in the LoadableDescriptors attribute",
1042 sig->as_C_string(), ik->name()->as_C_string());
1043 oop loader = ik->class_loader();
1044 Klass* klass = SystemDictionary::resolve_or_null(class_name,
1045 Handle(THREAD, loader), THREAD);
1046 if (HAS_PENDING_EXCEPTION) {
1047 CLEAR_PENDING_EXCEPTION;
1048 }
1049 if (klass != nullptr) {
1050 log_info(class, preload)("Preloading of class %s during linking of class %s "
1051 "(cause: LoadableDescriptors attribute) succeeded",
1052 class_name->as_C_string(), ik->name()->as_C_string());
1053 if (!klass->is_inline_klass()) {
1054 // Non value class are allowed by the current spec, but it could be an indication
1055 // of an issue so let's log a warning
1056 log_info(class, preload)("Preloading of class %s during linking of class %s "
1057 "(cause: LoadableDescriptors attribute) but loaded class is not a value class",
1058 class_name->as_C_string(), ik->name()->as_C_string());
1059 }
1060 } else {
1061 log_info(class, preload)("Preloading of class %s during linking of class %s "
1062 "(cause: LoadableDescriptors attribute) failed",
1063 class_name->as_C_string(), ik->name()->as_C_string());
1064 }
1065 }
1066 }
1067 }
1068
1069 void InstanceKlass::link_class(TRAPS) {
1070 assert(is_loaded(), "must be loaded");
1071 if (!is_linked()) {
1072 link_class_impl(CHECK);
1073 }
1074 }
1075
1076 // Called to verify that a class can link during initialization, without
1077 // throwing a VerifyError.
1078 bool InstanceKlass::link_class_or_fail(TRAPS) {
1079 assert(is_loaded(), "must be loaded");
1080 if (!is_linked()) {
1081 link_class_impl(CHECK_false);
1082 }
1083 return is_linked();
1084 }
1085
1086 bool InstanceKlass::link_class_impl(TRAPS) {
1087 if (CDSConfig::is_dumping_static_archive() && SystemDictionaryShared::has_class_failed_verification(this)) {
1088 // This is for CDS static dump only -- we use the in_error_state to indicate that
1119 THREAD_AND_LOCATION,
1120 vmSymbols::java_lang_IncompatibleClassChangeError(),
1121 "class %s has interface %s as super class",
1122 external_name(),
1123 super_klass->external_name()
1124 );
1125 return false;
1126 }
1127
1128 super_klass->link_class_impl(CHECK_false);
1129 }
1130
1131 // link all interfaces implemented by this class before linking this class
1132 Array<InstanceKlass*>* interfaces = local_interfaces();
1133 int num_interfaces = interfaces->length();
1134 for (int index = 0; index < num_interfaces; index++) {
1135 InstanceKlass* interk = interfaces->at(index);
1136 interk->link_class_impl(CHECK_false);
1137 }
1138
1139 if (Arguments::is_valhalla_enabled()) {
1140 // Aggressively preloading all classes from the LoadableDescriptors attribute
1141 // so inline classes can be scalarized in the calling conventions computed below
1142 load_classes_from_loadable_descriptors_attribute(this, THREAD);
1143 assert(!HAS_PENDING_EXCEPTION, "Shouldn't have pending exceptions from call above");
1144 }
1145
1146 // in case the class is linked in the process of linking its superclasses
1147 if (is_linked()) {
1148 return true;
1149 }
1150
1151 // trace only the link time for this klass that includes
1152 // the verification time
1153 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
1154 ClassLoader::perf_class_link_selftime(),
1155 ClassLoader::perf_classes_linked(),
1156 jt->get_thread_stat()->perf_recursion_counts_addr(),
1157 jt->get_thread_stat()->perf_timers_addr(),
1158 PerfClassTraceTime::CLASS_LINK);
1159
1160 // verification & rewriting
1161 {
1162 HandleMark hm(THREAD);
1163 Handle h_init_lock(THREAD, init_lock());
1164 ObjectLocker ol(h_init_lock, CHECK_PREEMPTABLE_false);
1165 // Don't allow preemption if we link/initialize classes below,
1449 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1450 ss.as_string(), cause);
1451 }
1452 } else {
1453
1454 // Step 6
1455 set_init_state(being_initialized);
1456 set_init_thread(jt);
1457 if (debug_logging_enabled) {
1458 ResourceMark rm(jt);
1459 log_debug(class, init)("Thread \"%s\" is initializing %s",
1460 jt->name(), external_name());
1461 }
1462 }
1463 }
1464
1465 // Block preemption once we are the initializer thread. Unmounting now
1466 // would complicate the reentrant case (identity is platform thread).
1467 NoPreemptMark npm(THREAD);
1468
1469 // Pre-allocating an all-zero value to be used to reset nullable flat storages
1470 if (is_inline_klass()) {
1471 InlineKlass* vk = InlineKlass::cast(this);
1472 if (vk->supports_nullable_layouts()) {
1473 oop val = vk->allocate_instance(THREAD);
1474 if (HAS_PENDING_EXCEPTION) {
1475 Handle e(THREAD, PENDING_EXCEPTION);
1476 CLEAR_PENDING_EXCEPTION;
1477 {
1478 EXCEPTION_MARK;
1479 add_initialization_error(THREAD, e);
1480 // Locks object, set state, and notify all waiting threads
1481 set_initialization_state_and_notify(initialization_error, THREAD);
1482 CLEAR_PENDING_EXCEPTION;
1483 }
1484 THROW_OOP(e());
1485 }
1486 vk->set_null_reset_value(val);
1487 }
1488 }
1489
1490 // Step 7
1491 // Next, if C is a class rather than an interface, initialize it's super class and super
1492 // interfaces.
1493 if (!is_interface()) {
1494 Klass* super_klass = super();
1495 if (super_klass != nullptr && super_klass->should_be_initialized()) {
1496 super_klass->initialize(THREAD);
1497 }
1498 // If C implements any interface that declares a non-static, concrete method,
1499 // the initialization of C triggers initialization of its super interfaces.
1500 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1501 // having a superinterface that declares, non-static, concrete methods
1502 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1503 initialize_super_interfaces(THREAD);
1504 }
1505
1506 // If any exceptions, complete abruptly, throwing the same exception as above.
1507 if (HAS_PENDING_EXCEPTION) {
1508 Handle e(THREAD, PENDING_EXCEPTION);
1509 CLEAR_PENDING_EXCEPTION;
1510 {
1511 EXCEPTION_MARK;
1512 add_initialization_error(THREAD, e);
1513 // Locks object, set state, and notify all waiting threads
1514 set_initialization_state_and_notify(initialization_error, THREAD);
1515 CLEAR_PENDING_EXCEPTION;
1516 }
1517 DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1518 THROW_OOP(e());
1519 }
1520 }
1521
1522 // Step 8
1523 {
1524 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1525 if (class_initializer() != nullptr) {
1526 // Timer includes any side effects of class initialization (resolution,
1527 // etc), but not recursive entry into call_class_initializer().
1528 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1529 ClassLoader::perf_class_init_selftime(),
1530 ClassLoader::perf_classes_inited(),
1531 jt->get_thread_stat()->perf_recursion_counts_addr(),
1532 jt->get_thread_stat()->perf_timers_addr(),
1533 PerfClassTraceTime::CLASS_CLINIT);
1534 call_class_initializer(THREAD);
1535 } else {
1536 // The elapsed time is so small it's not worth counting.
1537 if (UsePerfData) {
1538 ClassLoader::perf_classes_inited()->inc();
1539 }
1540 call_class_initializer(THREAD);
1541 }
1542
1543 if (has_strict_static_fields() && !HAS_PENDING_EXCEPTION) {
1544 // Step 9 also verifies that strict static fields have been initialized.
1545 // Status bits were set in ClassFileParser::post_process_parsed_stream.
1546 // After <clinit>, bits must all be clear, or else we must throw an error.
1547 // This is an extremely fast check, so we won't bother with a timer.
1548 assert(fields_status() != nullptr, "");
1549 Symbol* bad_strict_static = nullptr;
1550 for (int index = 0; index < fields_status()->length(); index++) {
1551 // Very fast loop over single byte array looking for a set bit.
1552 if (fields_status()->adr_at(index)->is_strict_static_unset()) {
1553 // This strict static field has not been set by the class initializer.
1554 // Note that in the common no-error case, we read no field metadata.
1555 // We only unpack it when we need to report an error.
1556 FieldInfo fi = field(index);
1557 bad_strict_static = fi.name(constants());
1558 if (debug_logging_enabled) {
1559 ResourceMark rm(jt);
1560 const char* msg = format_strict_static_message(bad_strict_static);
1561 log_debug(class, init)("%s", msg);
1562 } else {
1563 // If we are not logging, do not bother to look for a second offense.
1564 break;
1565 }
1566 }
1567 }
1568 if (bad_strict_static != nullptr) {
1569 throw_strict_static_exception(bad_strict_static, "is unset after initialization of", THREAD);
1570 }
1571 }
1572 }
1573
1574 // Step 9
1575 if (!HAS_PENDING_EXCEPTION) {
1576 set_initialization_state_and_notify(fully_initialized, CHECK);
1577 DEBUG_ONLY(vtable().verify(tty, true);)
1578 CompilationPolicy::replay_training_at_init(this, THREAD);
1579 }
1580 else {
1581 // Step 10 and 11
1582 Handle e(THREAD, PENDING_EXCEPTION);
1583 CLEAR_PENDING_EXCEPTION;
1584 // JVMTI has already reported the pending exception
1585 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1586 JvmtiExport::clear_detected_exception(jt);
1587 {
1588 EXCEPTION_MARK;
1589 add_initialization_error(THREAD, e);
1590 set_initialization_state_and_notify(initialization_error, THREAD);
1591 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1605 }
1606 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1607 }
1608
1609
1610 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1611 Handle h_init_lock(THREAD, init_lock());
1612 if (h_init_lock() != nullptr) {
1613 ObjectLocker ol(h_init_lock, THREAD);
1614 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1615 set_init_state(state);
1616 fence_and_clear_init_lock();
1617 ol.notify_all(CHECK);
1618 } else {
1619 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1620 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1621 set_init_state(state);
1622 }
1623 }
1624
1625 void InstanceKlass::notify_strict_static_access(int field_index, bool is_writing, TRAPS) {
1626 guarantee(field_index >= 0 && field_index < fields_status()->length(), "valid field index");
1627 DEBUG_ONLY(FieldInfo debugfi = field(field_index));
1628 assert(debugfi.access_flags().is_strict(), "");
1629 assert(debugfi.access_flags().is_static(), "");
1630 FieldStatus& fs = *fields_status()->adr_at(field_index);
1631 LogTarget(Trace, class, init) lt;
1632 if (lt.is_enabled()) {
1633 ResourceMark rm(THREAD);
1634 LogStream ls(lt);
1635 FieldInfo fi = field(field_index);
1636 ls.print("notify %s %s %s%s ",
1637 external_name(), is_writing? "Write" : "Read",
1638 fs.is_strict_static_unset() ? "Unset" : "(set)",
1639 fs.is_strict_static_unread() ? "+Unread" : "");
1640 fi.print(&ls, constants());
1641 }
1642 if (fs.is_strict_static_unset()) {
1643 assert(fs.is_strict_static_unread(), "ClassFileParser resp.");
1644 // If it is not set, there are only two reasonable things we can do here:
1645 // - mark it set if this is putstatic
1646 // - throw an error (Read-Before-Write) if this is getstatic
1647
1648 // The unset state is (or should be) transient, and observable only in one
1649 // thread during the execution of <clinit>. Something is wrong here as this
1650 // should not be possible
1651 guarantee(is_reentrant_initialization(THREAD), "unscoped access to strict static");
1652 if (is_writing) {
1653 // clear the "unset" bit, since the field is actually going to be written
1654 fs.update_strict_static_unset(false);
1655 } else {
1656 // throw an IllegalStateException, since we are reading before writing
1657 // see also InstanceKlass::initialize_impl, Step 8 (at end)
1658 Symbol* bad_strict_static = field(field_index).name(constants());
1659 throw_strict_static_exception(bad_strict_static, "is unset before first read in", CHECK);
1660 }
1661 } else {
1662 // Ensure no write after read for final strict statics
1663 FieldInfo fi = field(field_index);
1664 bool is_final = fi.access_flags().is_final();
1665 if (is_final) {
1666 // no final write after read, so observing a constant freezes it, as if <clinit> ended early
1667 // (maybe we could trust the constant a little earlier, before <clinit> ends)
1668 if (is_writing && !fs.is_strict_static_unread()) {
1669 Symbol* bad_strict_static = fi.name(constants());
1670 throw_strict_static_exception(bad_strict_static, "is set after read (as final) in", CHECK);
1671 } else if (!is_writing && fs.is_strict_static_unread()) {
1672 fs.update_strict_static_unread(false);
1673 }
1674 }
1675 }
1676 }
1677
1678 void InstanceKlass::throw_strict_static_exception(Symbol* field_name, const char* when, TRAPS) {
1679 ResourceMark rm(THREAD);
1680 const char* msg = format_strict_static_message(field_name, when);
1681 THROW_MSG(vmSymbols::java_lang_IllegalStateException(), msg);
1682 }
1683
1684 const char* InstanceKlass::format_strict_static_message(Symbol* field_name, const char* when) {
1685 stringStream ss;
1686 ss.print("Strict static \"%s\" %s %s",
1687 field_name->as_C_string(),
1688 when == nullptr ? "is unset in" : when,
1689 external_name());
1690 return ss.as_string();
1691 }
1692
1693 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1694 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1695 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1696 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1697
1698 DeoptimizationScope deopt_scope;
1699 {
1700 MutexLocker ml(current, Compile_lock);
1701
1702 set_init_state(InstanceKlass::loaded);
1703 // make sure init_state store is already done.
1704 // The compiler reads the hierarchy outside of the Compile_lock.
1705 // Access ordering is used to add to hierarchy.
1706
1707 // Link into hierarchy.
1708 append_to_sibling_list(); // add to superklass/sibling list
1709 process_interfaces(); // handle all "implements" declarations
1710
1711 // Now mark all code that depended on old class hierarchy.
1712 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1923 : vmSymbols::java_lang_IllegalAccessException(), external_name());
1924 }
1925 }
1926
1927 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
1928 // Need load-acquire for lock-free read
1929 if (array_klasses_acquire() == nullptr) {
1930
1931 // Recursively lock array allocation
1932 RecursiveLocker rl(MultiArray_lock, THREAD);
1933
1934 // Check if another thread created the array klass while we were waiting for the lock.
1935 if (array_klasses() == nullptr) {
1936 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
1937 // use 'release' to pair with lock-free load
1938 release_set_array_klasses(k);
1939 }
1940 }
1941
1942 // array_klasses() will always be set at this point
1943 ArrayKlass* ak = array_klasses();
1944 assert(ak != nullptr, "should be set");
1945 return ak->array_klass(n, THREAD);
1946 }
1947
1948 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1949 // Need load-acquire for lock-free read
1950 ArrayKlass* ak = array_klasses_acquire();
1951 if (ak == nullptr) {
1952 return nullptr;
1953 } else {
1954 return ak->array_klass_or_null(n);
1955 }
1956 }
1957
1958 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1959 return array_klass(1, THREAD);
1960 }
1961
1962 ArrayKlass* InstanceKlass::array_klass_or_null() {
1963 return array_klass_or_null(1);
1964 }
1965
1966 static int call_class_initializer_counter = 0; // for debugging
1967
1968 Method* InstanceKlass::class_initializer() const {
1969 Method* clinit = find_method(
1970 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1971 if (clinit != nullptr && clinit->is_class_initializer()) {
1972 return clinit;
1973 }
1974 return nullptr;
1975 }
1976
1977 void InstanceKlass::call_class_initializer(TRAPS) {
1978 if (ReplayCompiles &&
1979 (ReplaySuppressInitializers == 1 ||
1980 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1981 // Hide the existence of the initializer for the purpose of replaying the compile
1982 return;
1983 }
1984
1985 #if INCLUDE_CDS
1986 // This is needed to ensure the consistency of the archived heap objects.
1987 if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
1988 AOTClassInitializer::call_runtime_setup(THREAD, this);
1989 return;
1990 } else if (has_archived_enum_objs()) {
1991 assert(in_aot_cache(), "must be");
2060
2061 void InstanceKlass::mask_for(const methodHandle& method, int bci,
2062 InterpreterOopMap* entry_for) {
2063 // Lazily create the _oop_map_cache at first request.
2064 // Load_acquire is needed to safely get instance published with CAS by another thread.
2065 OopMapCache* oop_map_cache = AtomicAccess::load_acquire(&_oop_map_cache);
2066 if (oop_map_cache == nullptr) {
2067 // Try to install new instance atomically.
2068 oop_map_cache = new OopMapCache();
2069 OopMapCache* other = AtomicAccess::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
2070 if (other != nullptr) {
2071 // Someone else managed to install before us, ditch local copy and use the existing one.
2072 delete oop_map_cache;
2073 oop_map_cache = other;
2074 }
2075 }
2076 // _oop_map_cache is constant after init; lookup below does its own locking.
2077 oop_map_cache->lookup(method, bci, entry_for);
2078 }
2079
2080
2081 FieldInfo InstanceKlass::field(int index) const {
2082 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2083 if (fs.index() == index) {
2084 return fs.to_FieldInfo();
2085 }
2086 }
2087 fatal("Field not found");
2088 return FieldInfo();
2089 }
2090
2091 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
2092 JavaFieldStream fs(this);
2093 if (fs.lookup(name, sig)) {
2094 assert(fs.name() == name, "name must match");
2095 assert(fs.signature() == sig, "signature must match");
2096 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2097 return true;
2098 }
2099 return false;
2140
2141 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
2142 // search order according to newest JVM spec (5.4.3.2, p.167).
2143 // 1) search for field in current klass
2144 if (find_local_field(name, sig, fd)) {
2145 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
2146 }
2147 // 2) search for field recursively in direct superinterfaces
2148 if (is_static) {
2149 Klass* intf = find_interface_field(name, sig, fd);
2150 if (intf != nullptr) return intf;
2151 }
2152 // 3) apply field lookup recursively if superclass exists
2153 { InstanceKlass* supr = super();
2154 if (supr != nullptr) return supr->find_field(name, sig, is_static, fd);
2155 }
2156 // 4) otherwise field lookup fails
2157 return nullptr;
2158 }
2159
2160 bool InstanceKlass::contains_field_offset(int offset) {
2161 if (this->is_inline_klass()) {
2162 InlineKlass* vk = InlineKlass::cast(this);
2163 return offset >= vk->payload_offset() && offset < (vk->payload_offset() + vk->payload_size_in_bytes());
2164 } else {
2165 fieldDescriptor fd;
2166 return find_field_from_offset(offset, false, &fd);
2167 }
2168 }
2169
2170 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2171 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2172 if (fs.offset() == offset) {
2173 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2174 if (fd->is_static() == is_static) return true;
2175 }
2176 }
2177 return false;
2178 }
2179
2180
2181 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2182 const InstanceKlass* klass = this;
2183 while (klass != nullptr) {
2184 if (klass->find_local_field_from_offset(offset, is_static, fd)) {
2185 return true;
2186 }
2187 klass = klass->super();
2188 }
2191
2192
2193 void InstanceKlass::methods_do(void f(Method* method)) {
2194 // Methods aren't stable until they are loaded. This can be read outside
2195 // a lock through the ClassLoaderData for profiling
2196 // Redefined scratch classes are on the list and need to be cleaned
2197 if (!is_loaded() && !is_scratch_class()) {
2198 return;
2199 }
2200
2201 int len = methods()->length();
2202 for (int index = 0; index < len; index++) {
2203 Method* m = methods()->at(index);
2204 assert(m->is_method(), "must be method");
2205 f(m);
2206 }
2207 }
2208
2209
2210 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
2211 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2212 if (fs.access_flags().is_static()) {
2213 fieldDescriptor& fd = fs.field_descriptor();
2214 cl->do_field(&fd);
2215 }
2216 }
2217 }
2218
2219
2220 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
2221 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2222 if (fs.access_flags().is_static()) {
2223 fieldDescriptor& fd = fs.field_descriptor();
2224 f(&fd, mirror, CHECK);
2225 }
2226 }
2227 }
2228
2229 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
2230 InstanceKlass* super = this->super();
2231 if (super != nullptr) {
2232 super->do_nonstatic_fields(cl);
2233 }
2234 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2235 fieldDescriptor& fd = fs.field_descriptor();
2236 if (!fd.is_static()) {
2237 cl->do_field(&fd);
2238 }
2239 }
2240 }
2241
2532 }
2533
2534 // uncached_lookup_method searches both the local class methods array and all
2535 // superclasses methods arrays, skipping any overpass methods in superclasses,
2536 // and possibly skipping private methods.
2537 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2538 const Symbol* signature,
2539 OverpassLookupMode overpass_mode,
2540 PrivateLookupMode private_mode) const {
2541 OverpassLookupMode overpass_local_mode = overpass_mode;
2542 const InstanceKlass* klass = this;
2543 while (klass != nullptr) {
2544 Method* const method = klass->find_method_impl(name,
2545 signature,
2546 overpass_local_mode,
2547 StaticLookupMode::find,
2548 private_mode);
2549 if (method != nullptr) {
2550 return method;
2551 }
2552 if (name == vmSymbols::object_initializer_name()) {
2553 break; // <init> is never inherited
2554 }
2555 klass = klass->super();
2556 overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses
2557 }
2558 return nullptr;
2559 }
2560
2561 #ifdef ASSERT
2562 // search through class hierarchy and return true if this class or
2563 // one of the superclasses was redefined
2564 bool InstanceKlass::has_redefined_this_or_super() const {
2565 const InstanceKlass* klass = this;
2566 while (klass != nullptr) {
2567 if (klass->has_been_redefined()) {
2568 return true;
2569 }
2570 klass = klass->super();
2571 }
2572 return false;
2573 }
2574 #endif
2947 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2948
2949 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2950 / itableOffsetEntry::size();
2951
2952 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2953 if (ioe->interface_klass() != nullptr) {
2954 it->push(ioe->interface_klass_addr());
2955 itableMethodEntry* ime = ioe->first_method_entry(this);
2956 int n = klassItable::method_count_for_interface(ioe->interface_klass());
2957 for (int index = 0; index < n; index ++) {
2958 it->push(ime[index].method_addr());
2959 }
2960 }
2961 }
2962 }
2963
2964 it->push(&_nest_host);
2965 it->push(&_nest_members);
2966 it->push(&_permitted_subclasses);
2967 it->push(&_loadable_descriptors);
2968 it->push(&_acmp_maps_array, MetaspaceClosure::_writable);
2969 it->push(&_record_components);
2970 it->push(&_inline_layout_info_array, MetaspaceClosure::_writable);
2971 }
2972
2973 #if INCLUDE_CDS
2974 void InstanceKlass::remove_unshareable_info() {
2975
2976 if (is_linked()) {
2977 assert(can_be_verified_at_dumptime(), "must be");
2978 // Remember this so we can avoid walking the hierarchy at runtime.
2979 set_verified_at_dump_time();
2980 }
2981
2982 _misc_flags.set_has_init_deps_processed(false);
2983
2984 Klass::remove_unshareable_info();
2985
2986 if (SystemDictionaryShared::has_class_failed_verification(this)) {
2987 // Classes are attempted to link during dumping and may fail,
2988 // but these classes are still in the dictionary and class list in CLD.
2989 // If the class has failed verification, there is nothing else to remove.
2990 return;
2998
2999 { // Otherwise this needs to take out the Compile_lock.
3000 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
3001 init_implementor();
3002 }
3003
3004 // Call remove_unshareable_info() on other objects that belong to this class, except
3005 // for constants()->remove_unshareable_info(), which is called in a separate pass in
3006 // ArchiveBuilder::make_klasses_shareable(),
3007
3008 for (int i = 0; i < methods()->length(); i++) {
3009 Method* m = methods()->at(i);
3010 m->remove_unshareable_info();
3011 }
3012
3013 // do array classes also.
3014 if (array_klasses() != nullptr) {
3015 array_klasses()->remove_unshareable_info();
3016 }
3017
3018 // These are not allocated from metaspace. They are safe to set to nullptr.
3019 _source_debug_extension = nullptr;
3020 _dep_context = nullptr;
3021 _osr_nmethods_head = nullptr;
3022 #if INCLUDE_JVMTI
3023 _breakpoints = nullptr;
3024 _previous_versions = nullptr;
3025 _cached_class_file = nullptr;
3026 _jvmti_cached_class_field_map = nullptr;
3027 #endif
3028
3029 _init_thread = nullptr;
3030 _methods_jmethod_ids = nullptr;
3031 _jni_ids = nullptr;
3032 _oop_map_cache = nullptr;
3033 if (CDSConfig::is_dumping_method_handles() && HeapShared::is_lambda_proxy_klass(this)) {
3034 // keep _nest_host
3035 } else {
3036 // clear _nest_host to ensure re-load at runtime
3037 _nest_host = nullptr;
3038 }
3089 void InstanceKlass::compute_has_loops_flag_for_methods() {
3090 Array<Method*>* methods = this->methods();
3091 for (int index = 0; index < methods->length(); ++index) {
3092 Method* m = methods->at(index);
3093 if (!m->is_overpass()) { // work around JDK-8305771
3094 m->compute_has_loops_flag();
3095 }
3096 }
3097 }
3098
3099 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
3100 PackageEntry* pkg_entry, TRAPS) {
3101 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
3102 // before the InstanceKlass is added to the SystemDictionary. Make
3103 // sure the current state is <loaded.
3104 assert(!is_loaded(), "invalid init state");
3105 assert(!shared_loading_failed(), "Must not try to load failed class again");
3106 set_package(loader_data, pkg_entry, CHECK);
3107 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
3108
3109 if (is_inline_klass()) {
3110 InlineKlass::cast(this)->initialize_calling_convention(CHECK);
3111 }
3112
3113 Array<Method*>* methods = this->methods();
3114 int num_methods = methods->length();
3115 for (int index = 0; index < num_methods; ++index) {
3116 methods->at(index)->restore_unshareable_info(CHECK);
3117 }
3118 #if INCLUDE_JVMTI
3119 if (JvmtiExport::has_redefined_a_class()) {
3120 // Reinitialize vtable because RedefineClasses may have changed some
3121 // entries in this vtable for super classes so the CDS vtable might
3122 // point to old or obsolete entries. RedefineClasses doesn't fix up
3123 // vtables in the shared system dictionary, only the main one.
3124 // It also redefines the itable too so fix that too.
3125 // First fix any default methods that point to a super class that may
3126 // have been redefined.
3127 bool trace_name_printed = false;
3128 adjust_default_methods(&trace_name_printed);
3129 if (verified_at_dump_time()) {
3130 // Initialize vtable and itable for classes which can be verified at dump time.
3131 // Unlinked classes such as old classes with major version < 50 cannot be verified
3132 // at dump time.
3133 vtable().initialize_vtable();
3134 itable().initialize_itable();
3135 }
3136 }
3137 #endif // INCLUDE_JVMTI
3138
3139 // restore constant pool resolved references
3140 constants()->restore_unshareable_info(CHECK);
3141
3142 // Restore acmp_maps java array from the version stored in metadata.
3143 // if it cannot be found in the archive
3144 if (Arguments::is_valhalla_enabled() && has_acmp_maps_offset() && java_mirror()->obj_field(_acmp_maps_offset) == nullptr) {
3145 int acmp_maps_size = _acmp_maps_array->length();
3146 typeArrayOop map = oopFactory::new_intArray(acmp_maps_size, CHECK);
3147 typeArrayHandle map_h(THREAD, map);
3148 for (int i = 0; i < acmp_maps_size; i++) {
3149 map_h->int_at_put(i, _acmp_maps_array->at(i));
3150 }
3151 java_mirror()->obj_field_put(_acmp_maps_offset, map_h());
3152 }
3153
3154 if (array_klasses() != nullptr) {
3155 // To get a consistent list of classes we need MultiArray_lock to ensure
3156 // array classes aren't observed while they are being restored.
3157 RecursiveLocker rl(MultiArray_lock, THREAD);
3158 assert(this == ObjArrayKlass::cast(array_klasses())->bottom_klass(), "sanity");
3159 // Array classes have null protection domain.
3160 // --> see ArrayKlass::complete_create_array_klass()
3161 if (class_loader_data() == nullptr) {
3162 ResourceMark rm(THREAD);
3163 log_debug(cds)(" loader_data %s ", loader_data == nullptr ? "nullptr" : "non null");
3164 log_debug(cds)(" this %s array_klasses %s ", this->name()->as_C_string(), array_klasses()->name()->as_C_string());
3165 }
3166 assert(!array_klasses()->is_refined_objArray_klass(), "must be non-refined objarrayklass");
3167 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
3168 }
3169
3170 // Initialize @ValueBased class annotation if not already set in the archived klass.
3171 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
3172 set_is_value_based();
3173 }
3174
3175 DEBUG_ONLY(FieldInfoStream::validate_search_table(_constants, _fieldinfo_stream, _fieldinfo_search_table));
3176 }
3177
3178 bool InstanceKlass::can_be_verified_at_dumptime() const {
3179 if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(this)) {
3180 // This is a class that was dumped into the base archive, so we know
3181 // it was verified at dump time.
3182 return true;
3183 }
3184
3185 if (CDSConfig::is_preserving_verification_constraints()) {
3186 return true;
3302 constants()->release_C_heap_structures();
3303 }
3304 }
3305
3306 // The constant pool is on stack if any of the methods are executing or
3307 // referenced by handles.
3308 bool InstanceKlass::on_stack() const {
3309 return _constants->on_stack();
3310 }
3311
3312 Symbol* InstanceKlass::source_file_name() const { return _constants->source_file_name(); }
3313 u2 InstanceKlass::source_file_name_index() const { return _constants->source_file_name_index(); }
3314 void InstanceKlass::set_source_file_name_index(u2 sourcefile_index) { _constants->set_source_file_name_index(sourcefile_index); }
3315
3316 // minor and major version numbers of class file
3317 u2 InstanceKlass::minor_version() const { return _constants->minor_version(); }
3318 void InstanceKlass::set_minor_version(u2 minor_version) { _constants->set_minor_version(minor_version); }
3319 u2 InstanceKlass::major_version() const { return _constants->major_version(); }
3320 void InstanceKlass::set_major_version(u2 major_version) { _constants->set_major_version(major_version); }
3321
3322 bool InstanceKlass::supports_inline_types() const {
3323 return major_version() >= Verifier::VALUE_TYPES_MAJOR_VERSION && minor_version() == Verifier::JAVA_PREVIEW_MINOR_VERSION;
3324 }
3325
3326 const InstanceKlass* InstanceKlass::get_klass_version(int version) const {
3327 for (const InstanceKlass* ik = this; ik != nullptr; ik = ik->previous_versions()) {
3328 if (ik->constants()->version() == version) {
3329 return ik;
3330 }
3331 }
3332 return nullptr;
3333 }
3334
3335 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
3336 if (array == nullptr) {
3337 _source_debug_extension = nullptr;
3338 } else {
3339 // Adding one to the attribute length in order to store a null terminator
3340 // character could cause an overflow because the attribute length is
3341 // already coded with an u4 in the classfile, but in practice, it's
3342 // unlikely to happen.
3343 assert((length+1) > length, "Overflow checking");
3344 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
3345 for (int i = 0; i < length; i++) {
3346 sde[i] = array[i];
3347 }
3348 sde[length] = '\0';
3349 _source_debug_extension = sde;
3350 }
3351 }
3352
3353 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); }
3354 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); }
3355 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); }
3356
3357 const char* InstanceKlass::signature_name() const {
3358 return signature_name_of_carrier(JVM_SIGNATURE_CLASS);
3359 }
3360
3361 const char* InstanceKlass::signature_name_of_carrier(char c) const {
3362 // Get the internal name as a c string
3363 const char* src = (const char*) (name()->as_C_string());
3364 const int src_length = (int)strlen(src);
3365
3366 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
3367
3368 // Add L or Q as type indicator
3369 int dest_index = 0;
3370 dest[dest_index++] = c;
3371
3372 // Add the actual class name
3373 for (int src_index = 0; src_index < src_length; ) {
3374 dest[dest_index++] = src[src_index++];
3375 }
3376
3377 if (is_hidden()) { // Replace the last '+' with a '.'.
3378 for (int index = (int)src_length; index > 0; index--) {
3379 if (dest[index] == '+') {
3380 dest[index] = JVM_SIGNATURE_DOT;
3381 break;
3382 }
3383 }
3384 }
3385
3386 // Add the semicolon and the null
3387 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3388 dest[dest_index] = '\0';
3389 return dest;
3390 }
3631 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3632 constantPoolHandle i_cp(THREAD, constants());
3633 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3634 int ioff = iter.inner_class_info_index();
3635 if (ioff != 0) {
3636 // Check to see if the name matches the class we're looking for
3637 // before attempting to find the class.
3638 if (i_cp->klass_name_at_matches(this, ioff)) {
3639 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3640 if (this == inner_klass) {
3641 *ooff = iter.outer_class_info_index();
3642 *noff = iter.inner_name_index();
3643 return true;
3644 }
3645 }
3646 }
3647 }
3648 return false;
3649 }
3650
3651 void InstanceKlass::check_can_be_annotated_with_NullRestricted(InstanceKlass* type, Symbol* container_klass_name, TRAPS) {
3652 assert(type->is_instance_klass(), "Sanity check");
3653 if (type->is_identity_class()) {
3654 ResourceMark rm(THREAD);
3655 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
3656 err_msg("Class %s expects class %s to be a value class, but it is an identity class",
3657 container_klass_name->as_C_string(),
3658 type->external_name()));
3659 }
3660
3661 if (type->is_abstract()) {
3662 ResourceMark rm(THREAD);
3663 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
3664 err_msg("Class %s expects class %s to be concrete value type, but it is an abstract class",
3665 container_klass_name->as_C_string(),
3666 type->external_name()));
3667 }
3668 }
3669
3670 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3671 InstanceKlass* outer_klass = nullptr;
3672 *inner_is_member = false;
3673 int ooff = 0, noff = 0;
3674 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3675 if (has_inner_classes_attr) {
3676 constantPoolHandle i_cp(THREAD, constants());
3677 if (ooff != 0) {
3678 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3679 if (!ok->is_instance_klass()) {
3680 // If the outer class is not an instance klass then it cannot have
3681 // declared any inner classes.
3682 ResourceMark rm(THREAD);
3683 // Names are all known to be < 64k so we know this formatted message is not excessively large.
3684 Exceptions::fthrow(
3685 THREAD_AND_LOCATION,
3686 vmSymbols::java_lang_IncompatibleClassChangeError(),
3687 "%s and %s disagree on InnerClasses attribute",
3688 ok->external_name(),
3689 external_name());
3716 u2 InstanceKlass::compute_modifier_flags() const {
3717 u2 access = access_flags().as_unsigned_short();
3718
3719 // But check if it happens to be member class.
3720 InnerClassesIterator iter(this);
3721 for (; !iter.done(); iter.next()) {
3722 int ioff = iter.inner_class_info_index();
3723 // Inner class attribute can be zero, skip it.
3724 // Strange but true: JVM spec. allows null inner class refs.
3725 if (ioff == 0) continue;
3726
3727 // only look at classes that are already loaded
3728 // since we are looking for the flags for our self.
3729 Symbol* inner_name = constants()->klass_name_at(ioff);
3730 if (name() == inner_name) {
3731 // This is really a member class.
3732 access = iter.inner_access_flags();
3733 break;
3734 }
3735 }
3736 return access;
3737 }
3738
3739 jint InstanceKlass::jvmti_class_status() const {
3740 jint result = 0;
3741
3742 if (is_linked()) {
3743 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3744 }
3745
3746 if (is_initialized()) {
3747 assert(is_linked(), "Class status is not consistent");
3748 result |= JVMTI_CLASS_STATUS_INITIALIZED;
3749 }
3750 if (is_in_error_state()) {
3751 result |= JVMTI_CLASS_STATUS_ERROR;
3752 }
3753 return result;
3754 }
3755
3756 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
3970 }
3971 osr = osr->osr_link();
3972 }
3973
3974 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
3975 if (best != nullptr && best->comp_level() >= comp_level) {
3976 return best;
3977 }
3978 return nullptr;
3979 }
3980
3981 // -----------------------------------------------------------------------------------------------------
3982 // Printing
3983
3984 #define BULLET " - "
3985
3986 static const char* state_names[] = {
3987 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3988 };
3989
3990 static void print_vtable(address self, intptr_t* start, int len, outputStream* st) {
3991 ResourceMark rm;
3992 int* forward_refs = NEW_RESOURCE_ARRAY(int, len);
3993 for (int i = 0; i < len; i++) forward_refs[i] = 0;
3994 for (int i = 0; i < len; i++) {
3995 intptr_t e = start[i];
3996 st->print("%d : " INTPTR_FORMAT, i, e);
3997 if (forward_refs[i] != 0) {
3998 int from = forward_refs[i];
3999 int off = (int) start[from];
4000 st->print(" (offset %d <= [%d])", off, from);
4001 }
4002 if (MetaspaceObj::is_valid((Metadata*)e)) {
4003 st->print(" ");
4004 ((Metadata*)e)->print_value_on(st);
4005 } else if (self != nullptr && e > 0 && e < 0x10000) {
4006 address location = self + e;
4007 int index = (int)((intptr_t*)location - start);
4008 st->print(" (offset %d => [%d])", (int)e, index);
4009 if (index >= 0 && index < len)
4010 forward_refs[index] = i;
4011 }
4012 st->cr();
4013 }
4014 }
4015
4016 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
4017 return print_vtable(nullptr, reinterpret_cast<intptr_t*>(start), len, st);
4018 }
4019
4020 template<typename T>
4021 static void print_array_on(outputStream* st, Array<T>* array) {
4022 if (array == nullptr) { st->print_cr("nullptr"); return; }
4023 array->print_value_on(st); st->cr();
4024 if (Verbose || WizardMode) {
4025 for (int i = 0; i < array->length(); i++) {
4026 st->print("%d : ", i); array->at(i)->print_value_on(st); st->cr();
4027 }
4028 }
4029 }
4030
4031 static void print_array_on(outputStream* st, Array<int>* array) {
4032 if (array == nullptr) { st->print_cr("nullptr"); return; }
4033 array->print_value_on(st); st->cr();
4034 if (Verbose || WizardMode) {
4035 for (int i = 0; i < array->length(); i++) {
4036 st->print("%d : %d", i, array->at(i)); st->cr();
4037 }
4038 }
4039 }
4040
4041 const char* InstanceKlass::init_state_name() const {
4042 return state_names[init_state()];
4043 }
4044
4045 void InstanceKlass::print_on(outputStream* st) const {
4046 assert(is_klass(), "must be klass");
4047 Klass::print_on(st);
4048
4049 st->print(BULLET"instance size: %d", size_helper()); st->cr();
4050 st->print(BULLET"klass size: %d", size()); st->cr();
4051 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
4052 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
4053 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
4054 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
4055 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
4056 st->print(BULLET"sub: ");
4057 Klass* sub = subklass();
4058 int n;
4059 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
4060 if (n < MaxSubklassPrintSize) {
4061 sub->print_value_on(st);
4062 st->print(" ");
4063 }
4064 }
4065 if (n >= MaxSubklassPrintSize) st->print("(%zd more klasses...)", n - MaxSubklassPrintSize);
4066 st->cr();
4067
4068 if (is_interface()) {
4069 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
4070 if (nof_implementors() == 1) {
4071 st->print_cr(BULLET"implementor: ");
4072 st->print(" ");
4073 implementor()->print_value_on(st);
4074 st->cr();
4075 }
4076 }
4077
4078 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
4079 st->print(BULLET"methods: "); print_array_on(st, methods());
4080 st->print(BULLET"method ordering: "); print_array_on(st, method_ordering());
4081 if (default_methods() != nullptr) {
4082 st->print(BULLET"default_methods: "); print_array_on(st, default_methods());
4083 }
4084 print_on_maybe_null(st, BULLET"default vtable indices: ", default_vtable_indices());
4085 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
4086 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
4087
4088 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr();
4089
4090 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr();
4091 st->print(BULLET"secondary bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap); st->cr();
4092
4093 if (secondary_supers() != nullptr) {
4094 if (Verbose) {
4095 bool is_hashed = (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL);
4096 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length());
4097 for (int i = 0; i < _secondary_supers->length(); i++) {
4098 ResourceMark rm; // for external_name()
4099 Klass* secondary_super = _secondary_supers->at(i);
4100 st->print(BULLET"%2d:", i);
4101 if (is_hashed) {
4102 int home_slot = compute_home_slot(secondary_super, _secondary_supers_bitmap);
4122 print_on_maybe_null(st, BULLET"field type annotations: ", fields_type_annotations());
4123 {
4124 bool have_pv = false;
4125 // previous versions are linked together through the InstanceKlass
4126 for (InstanceKlass* pv_node = previous_versions();
4127 pv_node != nullptr;
4128 pv_node = pv_node->previous_versions()) {
4129 if (!have_pv)
4130 st->print(BULLET"previous version: ");
4131 have_pv = true;
4132 pv_node->constants()->print_value_on(st);
4133 }
4134 if (have_pv) st->cr();
4135 }
4136
4137 print_on_maybe_null(st, BULLET"generic signature: ", generic_signature());
4138 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
4139 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();
4140 print_on_maybe_null(st, BULLET"record components: ", record_components());
4141 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();
4142 st->print(BULLET"loadable descriptors: "); loadable_descriptors()->print_value_on(st); st->cr();
4143 if (java_mirror() != nullptr) {
4144 st->print(BULLET"java mirror: ");
4145 java_mirror()->print_value_on(st);
4146 st->cr();
4147 } else {
4148 st->print_cr(BULLET"java mirror: null");
4149 }
4150 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
4151 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);
4152 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
4153 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(nullptr, start_of_itable(), itable_length(), st);
4154 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
4155
4156 FieldPrinter print_static_field(st);
4157 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
4158 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
4159 FieldPrinter print_nonstatic_field(st);
4160 InstanceKlass* ik = const_cast<InstanceKlass*>(this);
4161 ik->print_nonstatic_fields(&print_nonstatic_field);
4162
4163 st->print(BULLET"non-static oop maps (%d entries): ", nonstatic_oop_map_count());
4164 OopMapBlock* map = start_of_nonstatic_oop_maps();
4165 OopMapBlock* end_map = map + nonstatic_oop_map_count();
4166 while (map < end_map) {
4167 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
4168 map++;
4169 }
4170 st->cr();
4171
4172 if (fieldinfo_search_table() != nullptr) {
4173 st->print_cr(BULLET"---- field info search table:");
4174 FieldInfoStream::print_search_table(st, _constants, _fieldinfo_stream, _fieldinfo_search_table);
4175 }
4176 }
4177
4178 void InstanceKlass::print_value_on(outputStream* st) const {
4179 assert(is_klass(), "must be klass");
4180 if (Verbose || WizardMode) access_flags().print_on(st);
4181 name()->print_value_on(st);
4182 }
4183
4184 void FieldPrinter::do_field(fieldDescriptor* fd) {
4185 for (int i = 0; i < _indent; i++) _st->print(" ");
4186 _st->print(BULLET);
4187 if (_obj == nullptr) {
4188 fd->print_on(_st, _base_offset);
4189 _st->cr();
4190 } else {
4191 fd->print_on_for(_st, _obj, _indent, _base_offset);
4192 if (!fd->field_flags().is_flat()) _st->cr();
4193 }
4194 }
4195
4196
4197 void InstanceKlass::oop_print_on(oop obj, outputStream* st, int indent, int base_offset) {
4198 Klass::oop_print_on(obj, st);
4199
4200 if (this == vmClasses::String_klass()) {
4201 typeArrayOop value = java_lang_String::value(obj);
4202 juint length = java_lang_String::length(obj);
4203 if (value != nullptr &&
4204 value->is_typeArray() &&
4205 length <= (juint) value->length()) {
4206 st->print(BULLET"string: ");
4207 java_lang_String::print(obj, st);
4208 st->cr();
4209 }
4210 }
4211
4212 st->print_cr(BULLET"---- fields (total size %zu words):", oop_size(obj));
4213 FieldPrinter print_field(st, obj, indent, base_offset);
4214 print_nonstatic_fields(&print_field);
4215
4216 if (this == vmClasses::Class_klass()) {
4217 st->print(BULLET"signature: ");
4218 java_lang_Class::print_signature(obj, st);
4219 st->cr();
4220 Klass* real_klass = java_lang_Class::as_Klass(obj);
4221 if (real_klass != nullptr && real_klass->is_instance_klass()) {
4222 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj));
4223 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
4224 }
4225 } else if (this == vmClasses::MethodType_klass()) {
4226 st->print(BULLET"signature: ");
4227 java_lang_invoke_MethodType::print_signature(obj, st);
4228 st->cr();
4229 }
4230 }
4231
4232 #ifndef PRODUCT
4233
|