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
442 log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
443 this->external_name(),
444 access ? "" : "NOT ",
445 k->external_name());
446 return access;
447 }
448
449 const char* InstanceKlass::nest_host_error() {
450 if (_nest_host_index == 0) {
451 return nullptr;
452 } else {
453 constantPoolHandle cph(Thread::current(), constants());
454 return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index);
455 }
456 }
457
458 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
459 const int size = InstanceKlass::size(parser.vtable_size(),
460 parser.itable_size(),
461 nonstatic_oop_map_size(parser.total_oop_map_count()),
462 parser.is_interface());
463
464 const Symbol* const class_name = parser.class_name();
465 assert(class_name != nullptr, "invariant");
466 ClassLoaderData* loader_data = parser.loader_data();
467 assert(loader_data != nullptr, "invariant");
468
469 InstanceKlass* ik;
470
471 // Allocation
472 if (parser.is_instance_ref_klass()) {
473 // java.lang.ref.Reference
474 ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
475 } else if (class_name == vmSymbols::java_lang_Class()) {
476 // mirror - java.lang.Class
477 ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
478 } else if (is_stack_chunk_class(class_name, loader_data)) {
479 // stack chunk
480 ik = new (loader_data, size, THREAD) InstanceStackChunkKlass(parser);
481 } else if (is_class_loader(class_name, parser)) {
482 // class loader - java.lang.ClassLoader
483 ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);
484 } else {
485 // normal
486 ik = new (loader_data, size, THREAD) InstanceKlass(parser);
487 }
488
489 if (ik != nullptr && UseCompressedClassPointers) {
490 assert(CompressedKlassPointers::is_encodable(ik),
491 "Klass " PTR_FORMAT "needs a narrow Klass ID, but is not encodable", p2i(ik));
492 }
493
494 // Check for pending exception before adding to the loader data and incrementing
495 // class count. Can get OOM here.
496 if (HAS_PENDING_EXCEPTION) {
497 return nullptr;
498 }
499
500 return ik;
501 }
502
503
504 // copy method ordering from resource area to Metaspace
505 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
506 if (m != nullptr) {
507 // allocate a new array and copy contents (memcpy?)
508 _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
509 for (int i = 0; i < m->length(); i++) {
510 _method_ordering->at_put(i, m->at(i));
511 }
512 } else {
513 _method_ordering = Universe::the_empty_int_array();
514 }
515 }
516
517 // create a new array of vtable_indices for default methods
518 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
519 Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
520 assert(default_vtable_indices() == nullptr, "only create once");
521 set_default_vtable_indices(vtable_indices);
522 return vtable_indices;
523 }
524
525
526 InstanceKlass::InstanceKlass() {
527 assert(CDSConfig::is_dumping_static_archive() || CDSConfig::is_using_archive(), "only for CDS");
528 }
529
530 InstanceKlass::InstanceKlass(const ClassFileParser& parser, KlassKind kind, ReferenceType reference_type) :
531 Klass(kind),
532 _nest_members(nullptr),
533 _nest_host(nullptr),
534 _permitted_subclasses(nullptr),
535 _record_components(nullptr),
536 _static_field_size(parser.static_field_size()),
537 _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
538 _itable_len(parser.itable_size()),
539 _nest_host_index(0),
540 _init_state(allocated),
541 _reference_type(reference_type),
542 _init_thread(nullptr)
543 {
544 set_vtable_length(parser.vtable_size());
545 set_access_flags(parser.access_flags());
546 if (parser.is_hidden()) set_is_hidden();
547 set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
548 false));
549
550 assert(nullptr == _methods, "underlying memory not zeroed?");
551 assert(is_instance_klass(), "is layout incorrect?");
552 assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
553 }
554
555 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
556 Array<Method*>* methods) {
557 if (methods != nullptr && methods != Universe::the_empty_method_array() &&
558 !methods->in_aot_cache()) {
559 for (int i = 0; i < methods->length(); i++) {
560 Method* method = methods->at(i);
561 if (method == nullptr) continue; // maybe null if error processing
562 // Only want to delete methods that are not executing for RedefineClasses.
563 // The previous version will point to them so they're not totally dangling
564 assert (!method->on_stack(), "shouldn't be called with methods on stack");
565 MetadataFactory::free_metadata(loader_data, method);
566 }
567 MetadataFactory::free_array<Method*>(loader_data, methods);
568 }
673
674 deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
675 set_transitive_interfaces(nullptr);
676 set_local_interfaces(nullptr);
677
678 if (fieldinfo_stream() != nullptr && !fieldinfo_stream()->in_aot_cache()) {
679 MetadataFactory::free_array<u1>(loader_data, fieldinfo_stream());
680 }
681 set_fieldinfo_stream(nullptr);
682
683 if (fieldinfo_search_table() != nullptr && !fieldinfo_search_table()->in_aot_cache()) {
684 MetadataFactory::free_array<u1>(loader_data, fieldinfo_search_table());
685 }
686 set_fieldinfo_search_table(nullptr);
687
688 if (fields_status() != nullptr && !fields_status()->in_aot_cache()) {
689 MetadataFactory::free_array<FieldStatus>(loader_data, fields_status());
690 }
691 set_fields_status(nullptr);
692
693 // If a method from a redefined class is using this constant pool, don't
694 // delete it, yet. The new class's previous version will point to this.
695 if (constants() != nullptr) {
696 assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
697 if (!constants()->in_aot_cache()) {
698 MetadataFactory::free_metadata(loader_data, constants());
699 }
700 // Delete any cached resolution errors for the constant pool
701 SystemDictionary::delete_resolution_error(constants());
702
703 set_constants(nullptr);
704 }
705
706 if (inner_classes() != nullptr &&
707 inner_classes() != Universe::the_empty_short_array() &&
708 !inner_classes()->in_aot_cache()) {
709 MetadataFactory::free_array<jushort>(loader_data, inner_classes());
710 }
711 set_inner_classes(nullptr);
712
713 if (nest_members() != nullptr &&
714 nest_members() != Universe::the_empty_short_array() &&
715 !nest_members()->in_aot_cache()) {
716 MetadataFactory::free_array<jushort>(loader_data, nest_members());
717 }
718 set_nest_members(nullptr);
719
720 if (permitted_subclasses() != nullptr &&
721 permitted_subclasses() != Universe::the_empty_short_array() &&
722 !permitted_subclasses()->in_aot_cache()) {
723 MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
724 }
725 set_permitted_subclasses(nullptr);
726
727 // We should deallocate the Annotations instance if it's not in shared spaces.
728 if (annotations() != nullptr && !annotations()->in_aot_cache()) {
729 MetadataFactory::free_metadata(loader_data, annotations());
730 }
731 set_annotations(nullptr);
732
733 SystemDictionaryShared::handle_class_unloading(this);
734
735 #if INCLUDE_CDS_JAVA_HEAP
736 if (CDSConfig::is_dumping_heap()) {
737 HeapShared::remove_scratch_objects(this);
738 }
739 #endif
740 }
741
742 bool InstanceKlass::is_record() const {
743 return _record_components != nullptr &&
744 is_final() &&
745 super() == vmClasses::Record_klass();
746 }
875 #ifdef ASSERT
876 {
877 Handle h_init_lock(THREAD, init_lock());
878 ObjectLocker ol(h_init_lock, THREAD);
879 assert(!is_initialized(), "sanity");
880 assert(!is_being_initialized(), "sanity");
881 assert(!is_in_error_state(), "sanity");
882 }
883 #endif
884
885 set_init_thread(THREAD);
886 set_initialization_state_and_notify(fully_initialized, CHECK);
887 }
888 #endif
889
890 bool InstanceKlass::verify_code(TRAPS) {
891 // 1) Verify the bytecodes
892 return Verifier::verify(this, should_verify_class(), THREAD);
893 }
894
895 void InstanceKlass::link_class(TRAPS) {
896 assert(is_loaded(), "must be loaded");
897 if (!is_linked()) {
898 link_class_impl(CHECK);
899 }
900 }
901
902 // Called to verify that a class can link during initialization, without
903 // throwing a VerifyError.
904 bool InstanceKlass::link_class_or_fail(TRAPS) {
905 assert(is_loaded(), "must be loaded");
906 if (!is_linked()) {
907 link_class_impl(CHECK_false);
908 }
909 return is_linked();
910 }
911
912 bool InstanceKlass::link_class_impl(TRAPS) {
913 if (CDSConfig::is_dumping_static_archive() && SystemDictionaryShared::has_class_failed_verification(this)) {
914 // This is for CDS static dump only -- we use the in_error_state to indicate that
945 THREAD_AND_LOCATION,
946 vmSymbols::java_lang_IncompatibleClassChangeError(),
947 "class %s has interface %s as super class",
948 external_name(),
949 super_klass->external_name()
950 );
951 return false;
952 }
953
954 super_klass->link_class_impl(CHECK_false);
955 }
956
957 // link all interfaces implemented by this class before linking this class
958 Array<InstanceKlass*>* interfaces = local_interfaces();
959 int num_interfaces = interfaces->length();
960 for (int index = 0; index < num_interfaces; index++) {
961 InstanceKlass* interk = interfaces->at(index);
962 interk->link_class_impl(CHECK_false);
963 }
964
965 // in case the class is linked in the process of linking its superclasses
966 if (is_linked()) {
967 return true;
968 }
969
970 // trace only the link time for this klass that includes
971 // the verification time
972 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
973 ClassLoader::perf_class_link_selftime(),
974 ClassLoader::perf_classes_linked(),
975 jt->get_thread_stat()->perf_recursion_counts_addr(),
976 jt->get_thread_stat()->perf_timers_addr(),
977 PerfClassTraceTime::CLASS_LINK);
978
979 // verification & rewriting
980 {
981 HandleMark hm(THREAD);
982 Handle h_init_lock(THREAD, init_lock());
983 ObjectLocker ol(h_init_lock, jt);
984 // rewritten will have been set if loader constraint error found
1249 ss.print("Could not initialize class %s", external_name());
1250 if (cause.is_null()) {
1251 THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), ss.as_string());
1252 } else {
1253 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1254 ss.as_string(), cause);
1255 }
1256 } else {
1257
1258 // Step 6
1259 set_init_state(being_initialized);
1260 set_init_thread(jt);
1261 if (debug_logging_enabled) {
1262 ResourceMark rm(jt);
1263 log_debug(class, init)("Thread \"%s\" is initializing %s",
1264 jt->name(), external_name());
1265 }
1266 }
1267 }
1268
1269 // Step 7
1270 // Next, if C is a class rather than an interface, initialize it's super class and super
1271 // interfaces.
1272 if (!is_interface()) {
1273 Klass* super_klass = super();
1274 if (super_klass != nullptr && super_klass->should_be_initialized()) {
1275 super_klass->initialize(THREAD);
1276 }
1277 // If C implements any interface that declares a non-static, concrete method,
1278 // the initialization of C triggers initialization of its super interfaces.
1279 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1280 // having a superinterface that declares, non-static, concrete methods
1281 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1282 initialize_super_interfaces(THREAD);
1283 }
1284
1285 // If any exceptions, complete abruptly, throwing the same exception as above.
1286 if (HAS_PENDING_EXCEPTION) {
1287 Handle e(THREAD, PENDING_EXCEPTION);
1288 CLEAR_PENDING_EXCEPTION;
1289 {
1290 EXCEPTION_MARK;
1291 add_initialization_error(THREAD, e);
1292 // Locks object, set state, and notify all waiting threads
1293 set_initialization_state_and_notify(initialization_error, THREAD);
1294 CLEAR_PENDING_EXCEPTION;
1295 }
1296 DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1297 THROW_OOP(e());
1298 }
1299 }
1300
1301
1302 // Step 8
1303 {
1304 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1305 if (class_initializer() != nullptr) {
1306 // Timer includes any side effects of class initialization (resolution,
1307 // etc), but not recursive entry into call_class_initializer().
1308 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1309 ClassLoader::perf_class_init_selftime(),
1310 ClassLoader::perf_classes_inited(),
1311 jt->get_thread_stat()->perf_recursion_counts_addr(),
1312 jt->get_thread_stat()->perf_timers_addr(),
1313 PerfClassTraceTime::CLASS_CLINIT);
1314 call_class_initializer(THREAD);
1315 } else {
1316 // The elapsed time is so small it's not worth counting.
1317 if (UsePerfData) {
1318 ClassLoader::perf_classes_inited()->inc();
1319 }
1320 call_class_initializer(THREAD);
1321 }
1322 }
1323
1324 // Step 9
1325 if (!HAS_PENDING_EXCEPTION) {
1326 set_initialization_state_and_notify(fully_initialized, CHECK);
1327 DEBUG_ONLY(vtable().verify(tty, true);)
1328 CompilationPolicy::replay_training_at_init(this, THREAD);
1329 }
1330 else {
1331 // Step 10 and 11
1332 Handle e(THREAD, PENDING_EXCEPTION);
1333 CLEAR_PENDING_EXCEPTION;
1334 // JVMTI has already reported the pending exception
1335 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1336 JvmtiExport::clear_detected_exception(jt);
1337 {
1338 EXCEPTION_MARK;
1339 add_initialization_error(THREAD, e);
1340 set_initialization_state_and_notify(initialization_error, THREAD);
1341 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1355 }
1356 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1357 }
1358
1359
1360 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1361 Handle h_init_lock(THREAD, init_lock());
1362 if (h_init_lock() != nullptr) {
1363 ObjectLocker ol(h_init_lock, THREAD);
1364 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1365 set_init_state(state);
1366 fence_and_clear_init_lock();
1367 ol.notify_all(CHECK);
1368 } else {
1369 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1370 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1371 set_init_state(state);
1372 }
1373 }
1374
1375 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1376 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1377 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1378 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1379
1380 DeoptimizationScope deopt_scope;
1381 {
1382 MutexLocker ml(current, Compile_lock);
1383
1384 set_init_state(InstanceKlass::loaded);
1385 // make sure init_state store is already done.
1386 // The compiler reads the hierarchy outside of the Compile_lock.
1387 // Access ordering is used to add to hierarchy.
1388
1389 // Link into hierarchy.
1390 append_to_sibling_list(); // add to superklass/sibling list
1391 process_interfaces(); // handle all "implements" declarations
1392
1393 // Now mark all code that depended on old class hierarchy.
1394 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1605 : vmSymbols::java_lang_IllegalAccessException(), external_name());
1606 }
1607 }
1608
1609 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
1610 // Need load-acquire for lock-free read
1611 if (array_klasses_acquire() == nullptr) {
1612
1613 // Recursively lock array allocation
1614 RecursiveLocker rl(MultiArray_lock, THREAD);
1615
1616 // Check if another thread created the array klass while we were waiting for the lock.
1617 if (array_klasses() == nullptr) {
1618 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
1619 // use 'release' to pair with lock-free load
1620 release_set_array_klasses(k);
1621 }
1622 }
1623
1624 // array_klasses() will always be set at this point
1625 ObjArrayKlass* ak = array_klasses();
1626 assert(ak != nullptr, "should be set");
1627 return ak->array_klass(n, THREAD);
1628 }
1629
1630 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1631 // Need load-acquire for lock-free read
1632 ObjArrayKlass* oak = array_klasses_acquire();
1633 if (oak == nullptr) {
1634 return nullptr;
1635 } else {
1636 return oak->array_klass_or_null(n);
1637 }
1638 }
1639
1640 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1641 return array_klass(1, THREAD);
1642 }
1643
1644 ArrayKlass* InstanceKlass::array_klass_or_null() {
1645 return array_klass_or_null(1);
1646 }
1647
1648 static int call_class_initializer_counter = 0; // for debugging
1649
1650 Method* InstanceKlass::class_initializer() const {
1651 Method* clinit = find_method(
1652 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1653 if (clinit != nullptr && clinit->has_valid_initializer_flags()) {
1654 return clinit;
1655 }
1656 return nullptr;
1657 }
1658
1659 void InstanceKlass::call_class_initializer(TRAPS) {
1660 if (ReplayCompiles &&
1661 (ReplaySuppressInitializers == 1 ||
1662 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1663 // Hide the existence of the initializer for the purpose of replaying the compile
1664 return;
1665 }
1666
1667 #if INCLUDE_CDS
1668 // This is needed to ensure the consistency of the archived heap objects.
1669 if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
1670 AOTClassInitializer::call_runtime_setup(THREAD, this);
1671 return;
1672 } else if (has_archived_enum_objs()) {
1673 assert(in_aot_cache(), "must be");
1742
1743 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1744 InterpreterOopMap* entry_for) {
1745 // Lazily create the _oop_map_cache at first request.
1746 // Load_acquire is needed to safely get instance published with CAS by another thread.
1747 OopMapCache* oop_map_cache = AtomicAccess::load_acquire(&_oop_map_cache);
1748 if (oop_map_cache == nullptr) {
1749 // Try to install new instance atomically.
1750 oop_map_cache = new OopMapCache();
1751 OopMapCache* other = AtomicAccess::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
1752 if (other != nullptr) {
1753 // Someone else managed to install before us, ditch local copy and use the existing one.
1754 delete oop_map_cache;
1755 oop_map_cache = other;
1756 }
1757 }
1758 // _oop_map_cache is constant after init; lookup below does its own locking.
1759 oop_map_cache->lookup(method, bci, entry_for);
1760 }
1761
1762 bool InstanceKlass::contains_field_offset(int offset) {
1763 fieldDescriptor fd;
1764 return find_field_from_offset(offset, false, &fd);
1765 }
1766
1767 FieldInfo InstanceKlass::field(int index) const {
1768 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
1769 if (fs.index() == index) {
1770 return fs.to_FieldInfo();
1771 }
1772 }
1773 fatal("Field not found");
1774 return FieldInfo();
1775 }
1776
1777 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1778 JavaFieldStream fs(this);
1779 if (fs.lookup(name, sig)) {
1780 assert(fs.name() == name, "name must match");
1781 assert(fs.signature() == sig, "signature must match");
1782 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
1783 return true;
1784 }
1785 return false;
1826
1827 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1828 // search order according to newest JVM spec (5.4.3.2, p.167).
1829 // 1) search for field in current klass
1830 if (find_local_field(name, sig, fd)) {
1831 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1832 }
1833 // 2) search for field recursively in direct superinterfaces
1834 if (is_static) {
1835 Klass* intf = find_interface_field(name, sig, fd);
1836 if (intf != nullptr) return intf;
1837 }
1838 // 3) apply field lookup recursively if superclass exists
1839 { InstanceKlass* supr = super();
1840 if (supr != nullptr) return supr->find_field(name, sig, is_static, fd);
1841 }
1842 // 4) otherwise field lookup fails
1843 return nullptr;
1844 }
1845
1846
1847 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1848 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1849 if (fs.offset() == offset) {
1850 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
1851 if (fd->is_static() == is_static) return true;
1852 }
1853 }
1854 return false;
1855 }
1856
1857
1858 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1859 const InstanceKlass* klass = this;
1860 while (klass != nullptr) {
1861 if (klass->find_local_field_from_offset(offset, is_static, fd)) {
1862 return true;
1863 }
1864 klass = klass->super();
1865 }
2209 }
2210
2211 // uncached_lookup_method searches both the local class methods array and all
2212 // superclasses methods arrays, skipping any overpass methods in superclasses,
2213 // and possibly skipping private methods.
2214 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2215 const Symbol* signature,
2216 OverpassLookupMode overpass_mode,
2217 PrivateLookupMode private_mode) const {
2218 OverpassLookupMode overpass_local_mode = overpass_mode;
2219 const InstanceKlass* klass = this;
2220 while (klass != nullptr) {
2221 Method* const method = klass->find_method_impl(name,
2222 signature,
2223 overpass_local_mode,
2224 StaticLookupMode::find,
2225 private_mode);
2226 if (method != nullptr) {
2227 return method;
2228 }
2229 klass = klass->super();
2230 overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses
2231 }
2232 return nullptr;
2233 }
2234
2235 #ifdef ASSERT
2236 // search through class hierarchy and return true if this class or
2237 // one of the superclasses was redefined
2238 bool InstanceKlass::has_redefined_this_or_super() const {
2239 const InstanceKlass* klass = this;
2240 while (klass != nullptr) {
2241 if (klass->has_been_redefined()) {
2242 return true;
2243 }
2244 klass = klass->super();
2245 }
2246 return false;
2247 }
2248 #endif
2621 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2622
2623 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2624 / itableOffsetEntry::size();
2625
2626 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2627 if (ioe->interface_klass() != nullptr) {
2628 it->push(ioe->interface_klass_addr());
2629 itableMethodEntry* ime = ioe->first_method_entry(this);
2630 int n = klassItable::method_count_for_interface(ioe->interface_klass());
2631 for (int index = 0; index < n; index ++) {
2632 it->push(ime[index].method_addr());
2633 }
2634 }
2635 }
2636 }
2637
2638 it->push(&_nest_host);
2639 it->push(&_nest_members);
2640 it->push(&_permitted_subclasses);
2641 it->push(&_record_components);
2642 }
2643
2644 #if INCLUDE_CDS
2645 void InstanceKlass::remove_unshareable_info() {
2646
2647 if (is_linked()) {
2648 assert(can_be_verified_at_dumptime(), "must be");
2649 // Remember this so we can avoid walking the hierarchy at runtime.
2650 set_verified_at_dump_time();
2651 }
2652
2653 _misc_flags.set_has_init_deps_processed(false);
2654
2655 Klass::remove_unshareable_info();
2656
2657 if (SystemDictionaryShared::has_class_failed_verification(this)) {
2658 // Classes are attempted to link during dumping and may fail,
2659 // but these classes are still in the dictionary and class list in CLD.
2660 // If the class has failed verification, there is nothing else to remove.
2661 return;
2669
2670 { // Otherwise this needs to take out the Compile_lock.
2671 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2672 init_implementor();
2673 }
2674
2675 // Call remove_unshareable_info() on other objects that belong to this class, except
2676 // for constants()->remove_unshareable_info(), which is called in a separate pass in
2677 // ArchiveBuilder::make_klasses_shareable(),
2678
2679 for (int i = 0; i < methods()->length(); i++) {
2680 Method* m = methods()->at(i);
2681 m->remove_unshareable_info();
2682 }
2683
2684 // do array classes also.
2685 if (array_klasses() != nullptr) {
2686 array_klasses()->remove_unshareable_info();
2687 }
2688
2689 // These are not allocated from metaspace. They are safe to set to null.
2690 _source_debug_extension = nullptr;
2691 _dep_context = nullptr;
2692 _osr_nmethods_head = nullptr;
2693 #if INCLUDE_JVMTI
2694 _breakpoints = nullptr;
2695 _previous_versions = nullptr;
2696 _cached_class_file = nullptr;
2697 _jvmti_cached_class_field_map = nullptr;
2698 #endif
2699
2700 _init_thread = nullptr;
2701 _methods_jmethod_ids = nullptr;
2702 _jni_ids = nullptr;
2703 _oop_map_cache = nullptr;
2704 if (CDSConfig::is_dumping_method_handles() && HeapShared::is_lambda_proxy_klass(this)) {
2705 // keep _nest_host
2706 } else {
2707 // clear _nest_host to ensure re-load at runtime
2708 _nest_host = nullptr;
2709 }
2760 void InstanceKlass::compute_has_loops_flag_for_methods() {
2761 Array<Method*>* methods = this->methods();
2762 for (int index = 0; index < methods->length(); ++index) {
2763 Method* m = methods->at(index);
2764 if (!m->is_overpass()) { // work around JDK-8305771
2765 m->compute_has_loops_flag();
2766 }
2767 }
2768 }
2769
2770 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
2771 PackageEntry* pkg_entry, TRAPS) {
2772 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
2773 // before the InstanceKlass is added to the SystemDictionary. Make
2774 // sure the current state is <loaded.
2775 assert(!is_loaded(), "invalid init state");
2776 assert(!shared_loading_failed(), "Must not try to load failed class again");
2777 set_package(loader_data, pkg_entry, CHECK);
2778 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2779
2780 Array<Method*>* methods = this->methods();
2781 int num_methods = methods->length();
2782 for (int index = 0; index < num_methods; ++index) {
2783 methods->at(index)->restore_unshareable_info(CHECK);
2784 }
2785 #if INCLUDE_JVMTI
2786 if (JvmtiExport::has_redefined_a_class()) {
2787 // Reinitialize vtable because RedefineClasses may have changed some
2788 // entries in this vtable for super classes so the CDS vtable might
2789 // point to old or obsolete entries. RedefineClasses doesn't fix up
2790 // vtables in the shared system dictionary, only the main one.
2791 // It also redefines the itable too so fix that too.
2792 // First fix any default methods that point to a super class that may
2793 // have been redefined.
2794 bool trace_name_printed = false;
2795 adjust_default_methods(&trace_name_printed);
2796 if (verified_at_dump_time()) {
2797 // Initialize vtable and itable for classes which can be verified at dump time.
2798 // Unlinked classes such as old classes with major version < 50 cannot be verified
2799 // at dump time.
2800 vtable().initialize_vtable();
2801 itable().initialize_itable();
2802 }
2803 }
2804 #endif // INCLUDE_JVMTI
2805
2806 // restore constant pool resolved references
2807 constants()->restore_unshareable_info(CHECK);
2808
2809 if (array_klasses() != nullptr) {
2810 // To get a consistent list of classes we need MultiArray_lock to ensure
2811 // array classes aren't observed while they are being restored.
2812 RecursiveLocker rl(MultiArray_lock, THREAD);
2813 assert(this == array_klasses()->bottom_klass(), "sanity");
2814 // Array classes have null protection domain.
2815 // --> see ArrayKlass::complete_create_array_klass()
2816 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
2817 }
2818
2819 // Initialize @ValueBased class annotation if not already set in the archived klass.
2820 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
2821 set_is_value_based();
2822 }
2823
2824 DEBUG_ONLY(FieldInfoStream::validate_search_table(_constants, _fieldinfo_stream, _fieldinfo_search_table));
2825 }
2826
2827 bool InstanceKlass::can_be_verified_at_dumptime() const {
2828 if (AOTMetaspace::in_aot_cache(this)) {
2829 // This is a class that was dumped into the base archive, so we know
2830 // it was verified at dump time.
2831 return true;
2832 }
2833
2834 if (CDSConfig::is_preserving_verification_constraints()) {
2835 return true;
2951 constants()->release_C_heap_structures();
2952 }
2953 }
2954
2955 // The constant pool is on stack if any of the methods are executing or
2956 // referenced by handles.
2957 bool InstanceKlass::on_stack() const {
2958 return _constants->on_stack();
2959 }
2960
2961 Symbol* InstanceKlass::source_file_name() const { return _constants->source_file_name(); }
2962 u2 InstanceKlass::source_file_name_index() const { return _constants->source_file_name_index(); }
2963 void InstanceKlass::set_source_file_name_index(u2 sourcefile_index) { _constants->set_source_file_name_index(sourcefile_index); }
2964
2965 // minor and major version numbers of class file
2966 u2 InstanceKlass::minor_version() const { return _constants->minor_version(); }
2967 void InstanceKlass::set_minor_version(u2 minor_version) { _constants->set_minor_version(minor_version); }
2968 u2 InstanceKlass::major_version() const { return _constants->major_version(); }
2969 void InstanceKlass::set_major_version(u2 major_version) { _constants->set_major_version(major_version); }
2970
2971 const InstanceKlass* InstanceKlass::get_klass_version(int version) const {
2972 for (const InstanceKlass* ik = this; ik != nullptr; ik = ik->previous_versions()) {
2973 if (ik->constants()->version() == version) {
2974 return ik;
2975 }
2976 }
2977 return nullptr;
2978 }
2979
2980 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
2981 if (array == nullptr) {
2982 _source_debug_extension = nullptr;
2983 } else {
2984 // Adding one to the attribute length in order to store a null terminator
2985 // character could cause an overflow because the attribute length is
2986 // already coded with an u4 in the classfile, but in practice, it's
2987 // unlikely to happen.
2988 assert((length+1) > length, "Overflow checking");
2989 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2990 for (int i = 0; i < length; i++) {
2991 sde[i] = array[i];
2992 }
2993 sde[length] = '\0';
2994 _source_debug_extension = sde;
2995 }
2996 }
2997
2998 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); }
2999 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); }
3000 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); }
3001
3002 const char* InstanceKlass::signature_name() const {
3003
3004 // Get the internal name as a c string
3005 const char* src = (const char*) (name()->as_C_string());
3006 const int src_length = (int)strlen(src);
3007
3008 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
3009
3010 // Add L as type indicator
3011 int dest_index = 0;
3012 dest[dest_index++] = JVM_SIGNATURE_CLASS;
3013
3014 // Add the actual class name
3015 for (int src_index = 0; src_index < src_length; ) {
3016 dest[dest_index++] = src[src_index++];
3017 }
3018
3019 if (is_hidden()) { // Replace the last '+' with a '.'.
3020 for (int index = (int)src_length; index > 0; index--) {
3021 if (dest[index] == '+') {
3022 dest[index] = JVM_SIGNATURE_DOT;
3023 break;
3024 }
3025 }
3026 }
3027
3028 // Add the semicolon and the null
3029 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3030 dest[dest_index] = '\0';
3031 return dest;
3032 }
3273 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3274 constantPoolHandle i_cp(THREAD, constants());
3275 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3276 int ioff = iter.inner_class_info_index();
3277 if (ioff != 0) {
3278 // Check to see if the name matches the class we're looking for
3279 // before attempting to find the class.
3280 if (i_cp->klass_name_at_matches(this, ioff)) {
3281 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3282 if (this == inner_klass) {
3283 *ooff = iter.outer_class_info_index();
3284 *noff = iter.inner_name_index();
3285 return true;
3286 }
3287 }
3288 }
3289 }
3290 return false;
3291 }
3292
3293 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3294 InstanceKlass* outer_klass = nullptr;
3295 *inner_is_member = false;
3296 int ooff = 0, noff = 0;
3297 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3298 if (has_inner_classes_attr) {
3299 constantPoolHandle i_cp(THREAD, constants());
3300 if (ooff != 0) {
3301 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3302 if (!ok->is_instance_klass()) {
3303 // If the outer class is not an instance klass then it cannot have
3304 // declared any inner classes.
3305 ResourceMark rm(THREAD);
3306 // Names are all known to be < 64k so we know this formatted message is not excessively large.
3307 Exceptions::fthrow(
3308 THREAD_AND_LOCATION,
3309 vmSymbols::java_lang_IncompatibleClassChangeError(),
3310 "%s and %s disagree on InnerClasses attribute",
3311 ok->external_name(),
3312 external_name());
3339 u2 InstanceKlass::compute_modifier_flags() const {
3340 u2 access = access_flags().as_unsigned_short();
3341
3342 // But check if it happens to be member class.
3343 InnerClassesIterator iter(this);
3344 for (; !iter.done(); iter.next()) {
3345 int ioff = iter.inner_class_info_index();
3346 // Inner class attribute can be zero, skip it.
3347 // Strange but true: JVM spec. allows null inner class refs.
3348 if (ioff == 0) continue;
3349
3350 // only look at classes that are already loaded
3351 // since we are looking for the flags for our self.
3352 Symbol* inner_name = constants()->klass_name_at(ioff);
3353 if (name() == inner_name) {
3354 // This is really a member class.
3355 access = iter.inner_access_flags();
3356 break;
3357 }
3358 }
3359 // Remember to strip ACC_SUPER bit
3360 return (access & (~JVM_ACC_SUPER));
3361 }
3362
3363 jint InstanceKlass::jvmti_class_status() const {
3364 jint result = 0;
3365
3366 if (is_linked()) {
3367 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3368 }
3369
3370 if (is_initialized()) {
3371 assert(is_linked(), "Class status is not consistent");
3372 result |= JVMTI_CLASS_STATUS_INITIALIZED;
3373 }
3374 if (is_in_error_state()) {
3375 result |= JVMTI_CLASS_STATUS_ERROR;
3376 }
3377 return result;
3378 }
3379
3380 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
3594 }
3595 osr = osr->osr_link();
3596 }
3597
3598 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
3599 if (best != nullptr && best->comp_level() >= comp_level) {
3600 return best;
3601 }
3602 return nullptr;
3603 }
3604
3605 // -----------------------------------------------------------------------------------------------------
3606 // Printing
3607
3608 #define BULLET " - "
3609
3610 static const char* state_names[] = {
3611 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3612 };
3613
3614 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3615 for (int i = 0; i < len; i++) {
3616 intptr_t e = start[i];
3617 st->print("%d : " INTPTR_FORMAT, i, e);
3618 if (MetaspaceObj::is_valid((Metadata*)e)) {
3619 st->print(" ");
3620 ((Metadata*)e)->print_value_on(st);
3621 }
3622 st->cr();
3623 }
3624 }
3625
3626 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3627 return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3628 }
3629
3630 const char* InstanceKlass::init_state_name() const {
3631 return state_names[init_state()];
3632 }
3633
3634 void InstanceKlass::print_on(outputStream* st) const {
3635 assert(is_klass(), "must be klass");
3636 Klass::print_on(st);
3637
3638 st->print(BULLET"instance size: %d", size_helper()); st->cr();
3639 st->print(BULLET"klass size: %d", size()); st->cr();
3640 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
3641 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
3642 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
3643 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
3644 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3645 st->print(BULLET"sub: ");
3646 Klass* sub = subklass();
3647 int n;
3648 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3649 if (n < MaxSubklassPrintSize) {
3650 sub->print_value_on(st);
3651 st->print(" ");
3652 }
3653 }
3654 if (n >= MaxSubklassPrintSize) st->print("(%zd more klasses...)", n - MaxSubklassPrintSize);
3655 st->cr();
3656
3657 if (is_interface()) {
3658 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
3659 if (nof_implementors() == 1) {
3660 st->print_cr(BULLET"implementor: ");
3661 st->print(" ");
3662 implementor()->print_value_on(st);
3663 st->cr();
3664 }
3665 }
3666
3667 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3668 st->print(BULLET"methods: "); methods()->print_value_on(st); st->cr();
3669 if (Verbose || WizardMode) {
3670 Array<Method*>* method_array = methods();
3671 for (int i = 0; i < method_array->length(); i++) {
3672 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3673 }
3674 }
3675 st->print(BULLET"method ordering: "); method_ordering()->print_value_on(st); st->cr();
3676 if (default_methods() != nullptr) {
3677 st->print(BULLET"default_methods: "); default_methods()->print_value_on(st); st->cr();
3678 if (Verbose) {
3679 Array<Method*>* method_array = default_methods();
3680 for (int i = 0; i < method_array->length(); i++) {
3681 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3682 }
3683 }
3684 }
3685 print_on_maybe_null(st, BULLET"default vtable indices: ", default_vtable_indices());
3686 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
3687 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3688
3689 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr();
3690
3691 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr();
3692 st->print(BULLET"secondary bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap); st->cr();
3693
3694 if (secondary_supers() != nullptr) {
3695 if (Verbose) {
3696 bool is_hashed = (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL);
3697 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length());
3698 for (int i = 0; i < _secondary_supers->length(); i++) {
3699 ResourceMark rm; // for external_name()
3700 Klass* secondary_super = _secondary_supers->at(i);
3701 st->print(BULLET"%2d:", i);
3702 if (is_hashed) {
3703 int home_slot = compute_home_slot(secondary_super, _secondary_supers_bitmap);
3723 print_on_maybe_null(st, BULLET"field type annotations: ", fields_type_annotations());
3724 {
3725 bool have_pv = false;
3726 // previous versions are linked together through the InstanceKlass
3727 for (InstanceKlass* pv_node = previous_versions();
3728 pv_node != nullptr;
3729 pv_node = pv_node->previous_versions()) {
3730 if (!have_pv)
3731 st->print(BULLET"previous version: ");
3732 have_pv = true;
3733 pv_node->constants()->print_value_on(st);
3734 }
3735 if (have_pv) st->cr();
3736 }
3737
3738 print_on_maybe_null(st, BULLET"generic signature: ", generic_signature());
3739 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
3740 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();
3741 print_on_maybe_null(st, BULLET"record components: ", record_components());
3742 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();
3743 if (java_mirror() != nullptr) {
3744 st->print(BULLET"java mirror: ");
3745 java_mirror()->print_value_on(st);
3746 st->cr();
3747 } else {
3748 st->print_cr(BULLET"java mirror: null");
3749 }
3750 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3751 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);
3752 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3753 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_itable(), itable_length(), st);
3754 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3755
3756 FieldPrinter print_static_field(st);
3757 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3758 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3759 FieldPrinter print_nonstatic_field(st);
3760 InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3761 ik->print_nonstatic_fields(&print_nonstatic_field);
3762
3763 st->print(BULLET"non-static oop maps (%d entries): ", nonstatic_oop_map_count());
3764 OopMapBlock* map = start_of_nonstatic_oop_maps();
3765 OopMapBlock* end_map = map + nonstatic_oop_map_count();
3766 while (map < end_map) {
3767 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3768 map++;
3769 }
3770 st->cr();
3771
3772 if (fieldinfo_search_table() != nullptr) {
3773 st->print_cr(BULLET"---- field info search table:");
3774 FieldInfoStream::print_search_table(st, _constants, _fieldinfo_stream, _fieldinfo_search_table);
3775 }
3776 }
3777
3778 void InstanceKlass::print_value_on(outputStream* st) const {
3779 assert(is_klass(), "must be klass");
3780 if (Verbose || WizardMode) access_flags().print_on(st);
3781 name()->print_value_on(st);
3782 }
3783
3784 void FieldPrinter::do_field(fieldDescriptor* fd) {
3785 _st->print(BULLET);
3786 if (_obj == nullptr) {
3787 fd->print_on(_st);
3788 _st->cr();
3789 } else {
3790 fd->print_on_for(_st, _obj);
3791 _st->cr();
3792 }
3793 }
3794
3795
3796 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3797 Klass::oop_print_on(obj, st);
3798
3799 if (this == vmClasses::String_klass()) {
3800 typeArrayOop value = java_lang_String::value(obj);
3801 juint length = java_lang_String::length(obj);
3802 if (value != nullptr &&
3803 value->is_typeArray() &&
3804 length <= (juint) value->length()) {
3805 st->print(BULLET"string: ");
3806 java_lang_String::print(obj, st);
3807 st->cr();
3808 }
3809 }
3810
3811 st->print_cr(BULLET"---- fields (total size %zu words):", oop_size(obj));
3812 FieldPrinter print_field(st, obj);
3813 print_nonstatic_fields(&print_field);
3814
3815 if (this == vmClasses::Class_klass()) {
3816 st->print(BULLET"signature: ");
3817 java_lang_Class::print_signature(obj, st);
3818 st->cr();
3819 Klass* real_klass = java_lang_Class::as_Klass(obj);
3820 if (real_klass != nullptr && real_klass->is_instance_klass()) {
3821 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj));
3822 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3823 }
3824 } else if (this == vmClasses::MethodType_klass()) {
3825 st->print(BULLET"signature: ");
3826 java_lang_invoke_MethodType::print_signature(obj, st);
3827 st->cr();
3828 }
3829 }
3830
3831 #ifndef PRODUCT
3832
|
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
463 log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
464 this->external_name(),
465 access ? "" : "NOT ",
466 k->external_name());
467 return access;
468 }
469
470 const char* InstanceKlass::nest_host_error() {
471 if (_nest_host_index == 0) {
472 return nullptr;
473 } else {
474 constantPoolHandle cph(Thread::current(), constants());
475 return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index);
476 }
477 }
478
479 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
480 const int size = InstanceKlass::size(parser.vtable_size(),
481 parser.itable_size(),
482 nonstatic_oop_map_size(parser.total_oop_map_count()),
483 parser.is_interface(),
484 parser.is_inline_type());
485
486 const Symbol* const class_name = parser.class_name();
487 assert(class_name != nullptr, "invariant");
488 ClassLoaderData* loader_data = parser.loader_data();
489 assert(loader_data != nullptr, "invariant");
490
491 InstanceKlass* ik;
492
493 // Allocation
494 if (parser.is_instance_ref_klass()) {
495 // java.lang.ref.Reference
496 ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
497 } else if (class_name == vmSymbols::java_lang_Class()) {
498 // mirror - java.lang.Class
499 ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
500 } else if (is_stack_chunk_class(class_name, loader_data)) {
501 // stack chunk
502 ik = new (loader_data, size, THREAD) InstanceStackChunkKlass(parser);
503 } else if (is_class_loader(class_name, parser)) {
504 // class loader - java.lang.ClassLoader
505 ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);
506 } else if (parser.is_inline_type()) {
507 // inline type
508 ik = new (loader_data, size, THREAD) InlineKlass(parser);
509 } else {
510 // normal
511 ik = new (loader_data, size, THREAD) InstanceKlass(parser);
512 }
513
514 if (ik != nullptr && UseCompressedClassPointers) {
515 assert(CompressedKlassPointers::is_encodable(ik),
516 "Klass " PTR_FORMAT "needs a narrow Klass ID, but is not encodable", p2i(ik));
517 }
518
519 // Check for pending exception before adding to the loader data and incrementing
520 // class count. Can get OOM here.
521 if (HAS_PENDING_EXCEPTION) {
522 return nullptr;
523 }
524
525 #ifdef ASSERT
526 ik->bounds_check((address) ik->start_of_vtable(), false, size);
527 ik->bounds_check((address) ik->start_of_itable(), false, size);
528 ik->bounds_check((address) ik->end_of_itable(), true, size);
529 ik->bounds_check((address) ik->end_of_nonstatic_oop_maps(), true, size);
530 #endif //ASSERT
531 return ik;
532 }
533
534 #ifndef PRODUCT
535 bool InstanceKlass::bounds_check(address addr, bool edge_ok, intptr_t size_in_bytes) const {
536 const char* bad = nullptr;
537 address end = nullptr;
538 if (addr < (address)this) {
539 bad = "before";
540 } else if (addr == (address)this) {
541 if (edge_ok) return true;
542 bad = "just before";
543 } else if (addr == (end = (address)this + sizeof(intptr_t) * (size_in_bytes < 0 ? size() : size_in_bytes))) {
544 if (edge_ok) return true;
545 bad = "just after";
546 } else if (addr > end) {
547 bad = "after";
548 } else {
549 return true;
550 }
551 tty->print_cr("%s object bounds: " INTPTR_FORMAT " [" INTPTR_FORMAT ".." INTPTR_FORMAT "]",
552 bad, (intptr_t)addr, (intptr_t)this, (intptr_t)end);
553 Verbose = WizardMode = true; this->print(); //@@
554 return false;
555 }
556 #endif //PRODUCT
557
558 // copy method ordering from resource area to Metaspace
559 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
560 if (m != nullptr) {
561 // allocate a new array and copy contents (memcpy?)
562 _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
563 for (int i = 0; i < m->length(); i++) {
564 _method_ordering->at_put(i, m->at(i));
565 }
566 } else {
567 _method_ordering = Universe::the_empty_int_array();
568 }
569 }
570
571 // create a new array of vtable_indices for default methods
572 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
573 Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
574 assert(default_vtable_indices() == nullptr, "only create once");
575 set_default_vtable_indices(vtable_indices);
576 return vtable_indices;
577 }
578
579
580 InstanceKlass::InstanceKlass() {
581 assert(CDSConfig::is_dumping_static_archive() || CDSConfig::is_using_archive(), "only for CDS");
582 }
583
584 InstanceKlass::InstanceKlass(const ClassFileParser& parser, KlassKind kind, markWord prototype_header, ReferenceType reference_type) :
585 Klass(kind, prototype_header),
586 _nest_members(nullptr),
587 _nest_host(nullptr),
588 _permitted_subclasses(nullptr),
589 _record_components(nullptr),
590 _static_field_size(parser.static_field_size()),
591 _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
592 _itable_len(parser.itable_size()),
593 _nest_host_index(0),
594 _init_state(allocated),
595 _reference_type(reference_type),
596 _init_thread(nullptr),
597 _inline_layout_info_array(nullptr),
598 _loadable_descriptors(nullptr),
599 _adr_inlineklass_fixed_block(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_inline_fields()) {
607 set_has_inline_type_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::deallocate_methods(ClassLoaderData* loader_data,
616 Array<Method*>* methods) {
617 if (methods != nullptr && methods != Universe::the_empty_method_array() &&
618 !methods->in_aot_cache()) {
619 for (int i = 0; i < methods->length(); i++) {
620 Method* method = methods->at(i);
621 if (method == nullptr) continue; // maybe null if error processing
622 // Only want to delete methods that are not executing for RedefineClasses.
623 // The previous version will point to them so they're not totally dangling
624 assert (!method->on_stack(), "shouldn't be called with methods on stack");
625 MetadataFactory::free_metadata(loader_data, method);
626 }
627 MetadataFactory::free_array<Method*>(loader_data, methods);
628 }
733
734 deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
735 set_transitive_interfaces(nullptr);
736 set_local_interfaces(nullptr);
737
738 if (fieldinfo_stream() != nullptr && !fieldinfo_stream()->in_aot_cache()) {
739 MetadataFactory::free_array<u1>(loader_data, fieldinfo_stream());
740 }
741 set_fieldinfo_stream(nullptr);
742
743 if (fieldinfo_search_table() != nullptr && !fieldinfo_search_table()->in_aot_cache()) {
744 MetadataFactory::free_array<u1>(loader_data, fieldinfo_search_table());
745 }
746 set_fieldinfo_search_table(nullptr);
747
748 if (fields_status() != nullptr && !fields_status()->in_aot_cache()) {
749 MetadataFactory::free_array<FieldStatus>(loader_data, fields_status());
750 }
751 set_fields_status(nullptr);
752
753 if (inline_layout_info_array() != nullptr) {
754 MetadataFactory::free_array<InlineLayoutInfo>(loader_data, inline_layout_info_array());
755 }
756 set_inline_layout_info_array(nullptr);
757
758 // If a method from a redefined class is using this constant pool, don't
759 // delete it, yet. The new class's previous version will point to this.
760 if (constants() != nullptr) {
761 assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
762 if (!constants()->in_aot_cache()) {
763 MetadataFactory::free_metadata(loader_data, constants());
764 }
765 // Delete any cached resolution errors for the constant pool
766 SystemDictionary::delete_resolution_error(constants());
767
768 set_constants(nullptr);
769 }
770
771 if (inner_classes() != nullptr &&
772 inner_classes() != Universe::the_empty_short_array() &&
773 !inner_classes()->in_aot_cache()) {
774 MetadataFactory::free_array<jushort>(loader_data, inner_classes());
775 }
776 set_inner_classes(nullptr);
777
778 if (nest_members() != nullptr &&
779 nest_members() != Universe::the_empty_short_array() &&
780 !nest_members()->in_aot_cache()) {
781 MetadataFactory::free_array<jushort>(loader_data, nest_members());
782 }
783 set_nest_members(nullptr);
784
785 if (permitted_subclasses() != nullptr &&
786 permitted_subclasses() != Universe::the_empty_short_array() &&
787 !permitted_subclasses()->in_aot_cache()) {
788 MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
789 }
790 set_permitted_subclasses(nullptr);
791
792 if (loadable_descriptors() != nullptr &&
793 loadable_descriptors() != Universe::the_empty_short_array() &&
794 !loadable_descriptors()->in_aot_cache()) {
795 MetadataFactory::free_array<jushort>(loader_data, loadable_descriptors());
796 }
797 set_loadable_descriptors(nullptr);
798
799 // We should deallocate the Annotations instance if it's not in shared spaces.
800 if (annotations() != nullptr && !annotations()->in_aot_cache()) {
801 MetadataFactory::free_metadata(loader_data, annotations());
802 }
803 set_annotations(nullptr);
804
805 SystemDictionaryShared::handle_class_unloading(this);
806
807 #if INCLUDE_CDS_JAVA_HEAP
808 if (CDSConfig::is_dumping_heap()) {
809 HeapShared::remove_scratch_objects(this);
810 }
811 #endif
812 }
813
814 bool InstanceKlass::is_record() const {
815 return _record_components != nullptr &&
816 is_final() &&
817 super() == vmClasses::Record_klass();
818 }
947 #ifdef ASSERT
948 {
949 Handle h_init_lock(THREAD, init_lock());
950 ObjectLocker ol(h_init_lock, THREAD);
951 assert(!is_initialized(), "sanity");
952 assert(!is_being_initialized(), "sanity");
953 assert(!is_in_error_state(), "sanity");
954 }
955 #endif
956
957 set_init_thread(THREAD);
958 set_initialization_state_and_notify(fully_initialized, CHECK);
959 }
960 #endif
961
962 bool InstanceKlass::verify_code(TRAPS) {
963 // 1) Verify the bytecodes
964 return Verifier::verify(this, should_verify_class(), THREAD);
965 }
966
967 static void load_classes_from_loadable_descriptors_attribute(InstanceKlass *ik, TRAPS) {
968 ResourceMark rm(THREAD);
969 if (ik->loadable_descriptors() != nullptr && PreloadClasses) {
970 HandleMark hm(THREAD);
971 for (int i = 0; i < ik->loadable_descriptors()->length(); i++) {
972 Symbol* sig = ik->constants()->symbol_at(ik->loadable_descriptors()->at(i));
973 if (!Signature::has_envelope(sig)) continue;
974 TempNewSymbol class_name = Signature::strip_envelope(sig);
975 if (class_name == ik->name()) continue;
976 log_info(class, preload)("Preloading of class %s during linking of class %s "
977 "because of the class is listed in the LoadableDescriptors attribute",
978 sig->as_C_string(), ik->name()->as_C_string());
979 oop loader = ik->class_loader();
980 Klass* klass = SystemDictionary::resolve_or_null(class_name,
981 Handle(THREAD, loader), THREAD);
982 if (HAS_PENDING_EXCEPTION) {
983 CLEAR_PENDING_EXCEPTION;
984 }
985 if (klass != nullptr) {
986 log_info(class, preload)("Preloading of class %s during linking of class %s "
987 "(cause: LoadableDescriptors attribute) succeeded",
988 class_name->as_C_string(), ik->name()->as_C_string());
989 if (!klass->is_inline_klass()) {
990 // Non value class are allowed by the current spec, but it could be an indication
991 // of an issue so let's log a warning
992 log_warning(class, preload)("Preloading of class %s during linking of class %s "
993 "(cause: LoadableDescriptors attribute) but loaded class is not a value class",
994 class_name->as_C_string(), ik->name()->as_C_string());
995 }
996 } else {
997 log_warning(class, preload)("Preloading of class %s during linking of class %s "
998 "(cause: LoadableDescriptors attribute) failed",
999 class_name->as_C_string(), ik->name()->as_C_string());
1000 }
1001 }
1002 }
1003 }
1004
1005 void InstanceKlass::link_class(TRAPS) {
1006 assert(is_loaded(), "must be loaded");
1007 if (!is_linked()) {
1008 link_class_impl(CHECK);
1009 }
1010 }
1011
1012 // Called to verify that a class can link during initialization, without
1013 // throwing a VerifyError.
1014 bool InstanceKlass::link_class_or_fail(TRAPS) {
1015 assert(is_loaded(), "must be loaded");
1016 if (!is_linked()) {
1017 link_class_impl(CHECK_false);
1018 }
1019 return is_linked();
1020 }
1021
1022 bool InstanceKlass::link_class_impl(TRAPS) {
1023 if (CDSConfig::is_dumping_static_archive() && SystemDictionaryShared::has_class_failed_verification(this)) {
1024 // This is for CDS static dump only -- we use the in_error_state to indicate that
1055 THREAD_AND_LOCATION,
1056 vmSymbols::java_lang_IncompatibleClassChangeError(),
1057 "class %s has interface %s as super class",
1058 external_name(),
1059 super_klass->external_name()
1060 );
1061 return false;
1062 }
1063
1064 super_klass->link_class_impl(CHECK_false);
1065 }
1066
1067 // link all interfaces implemented by this class before linking this class
1068 Array<InstanceKlass*>* interfaces = local_interfaces();
1069 int num_interfaces = interfaces->length();
1070 for (int index = 0; index < num_interfaces; index++) {
1071 InstanceKlass* interk = interfaces->at(index);
1072 interk->link_class_impl(CHECK_false);
1073 }
1074
1075 if (EnableValhalla) {
1076 // Aggressively preloading all classes from the LoadableDescriptors attribute
1077 // so inline classes can be scalarized in the calling conventions computed below
1078 load_classes_from_loadable_descriptors_attribute(this, THREAD);
1079 assert(!HAS_PENDING_EXCEPTION, "Shouldn't have pending exceptions from call above");
1080 }
1081
1082 // in case the class is linked in the process of linking its superclasses
1083 if (is_linked()) {
1084 return true;
1085 }
1086
1087 // trace only the link time for this klass that includes
1088 // the verification time
1089 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
1090 ClassLoader::perf_class_link_selftime(),
1091 ClassLoader::perf_classes_linked(),
1092 jt->get_thread_stat()->perf_recursion_counts_addr(),
1093 jt->get_thread_stat()->perf_timers_addr(),
1094 PerfClassTraceTime::CLASS_LINK);
1095
1096 // verification & rewriting
1097 {
1098 HandleMark hm(THREAD);
1099 Handle h_init_lock(THREAD, init_lock());
1100 ObjectLocker ol(h_init_lock, jt);
1101 // rewritten will have been set if loader constraint error found
1366 ss.print("Could not initialize class %s", external_name());
1367 if (cause.is_null()) {
1368 THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), ss.as_string());
1369 } else {
1370 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1371 ss.as_string(), cause);
1372 }
1373 } else {
1374
1375 // Step 6
1376 set_init_state(being_initialized);
1377 set_init_thread(jt);
1378 if (debug_logging_enabled) {
1379 ResourceMark rm(jt);
1380 log_debug(class, init)("Thread \"%s\" is initializing %s",
1381 jt->name(), external_name());
1382 }
1383 }
1384 }
1385
1386 // Pre-allocating an all-zero value to be used to reset nullable flat storages
1387 if (is_inline_klass()) {
1388 InlineKlass* vk = InlineKlass::cast(this);
1389 if (vk->has_nullable_atomic_layout()) {
1390 oop val = vk->allocate_instance(THREAD);
1391 if (HAS_PENDING_EXCEPTION) {
1392 Handle e(THREAD, PENDING_EXCEPTION);
1393 CLEAR_PENDING_EXCEPTION;
1394 {
1395 EXCEPTION_MARK;
1396 add_initialization_error(THREAD, e);
1397 // Locks object, set state, and notify all waiting threads
1398 set_initialization_state_and_notify(initialization_error, THREAD);
1399 CLEAR_PENDING_EXCEPTION;
1400 }
1401 THROW_OOP(e());
1402 }
1403 vk->set_null_reset_value(val);
1404 }
1405 }
1406
1407 // Step 7
1408 // Next, if C is a class rather than an interface, initialize it's super class and super
1409 // interfaces.
1410 if (!is_interface()) {
1411 Klass* super_klass = super();
1412 if (super_klass != nullptr && super_klass->should_be_initialized()) {
1413 super_klass->initialize(THREAD);
1414 }
1415 // If C implements any interface that declares a non-static, concrete method,
1416 // the initialization of C triggers initialization of its super interfaces.
1417 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1418 // having a superinterface that declares, non-static, concrete methods
1419 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1420 initialize_super_interfaces(THREAD);
1421 }
1422
1423 // If any exceptions, complete abruptly, throwing the same exception as above.
1424 if (HAS_PENDING_EXCEPTION) {
1425 Handle e(THREAD, PENDING_EXCEPTION);
1426 CLEAR_PENDING_EXCEPTION;
1427 {
1428 EXCEPTION_MARK;
1429 add_initialization_error(THREAD, e);
1430 // Locks object, set state, and notify all waiting threads
1431 set_initialization_state_and_notify(initialization_error, THREAD);
1432 CLEAR_PENDING_EXCEPTION;
1433 }
1434 DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1435 THROW_OOP(e());
1436 }
1437 }
1438
1439 // Step 8
1440 {
1441 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1442 if (class_initializer() != nullptr) {
1443 // Timer includes any side effects of class initialization (resolution,
1444 // etc), but not recursive entry into call_class_initializer().
1445 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1446 ClassLoader::perf_class_init_selftime(),
1447 ClassLoader::perf_classes_inited(),
1448 jt->get_thread_stat()->perf_recursion_counts_addr(),
1449 jt->get_thread_stat()->perf_timers_addr(),
1450 PerfClassTraceTime::CLASS_CLINIT);
1451 call_class_initializer(THREAD);
1452 } else {
1453 // The elapsed time is so small it's not worth counting.
1454 if (UsePerfData) {
1455 ClassLoader::perf_classes_inited()->inc();
1456 }
1457 call_class_initializer(THREAD);
1458 }
1459
1460 if (has_strict_static_fields() && !HAS_PENDING_EXCEPTION) {
1461 // Step 9 also verifies that strict static fields have been initialized.
1462 // Status bits were set in ClassFileParser::post_process_parsed_stream.
1463 // After <clinit>, bits must all be clear, or else we must throw an error.
1464 // This is an extremely fast check, so we won't bother with a timer.
1465 assert(fields_status() != nullptr, "");
1466 Symbol* bad_strict_static = nullptr;
1467 for (int index = 0; index < fields_status()->length(); index++) {
1468 // Very fast loop over single byte array looking for a set bit.
1469 if (fields_status()->adr_at(index)->is_strict_static_unset()) {
1470 // This strict static field has not been set by the class initializer.
1471 // Note that in the common no-error case, we read no field metadata.
1472 // We only unpack it when we need to report an error.
1473 FieldInfo fi = field(index);
1474 bad_strict_static = fi.name(constants());
1475 if (debug_logging_enabled) {
1476 ResourceMark rm(jt);
1477 const char* msg = format_strict_static_message(bad_strict_static);
1478 log_debug(class, init)("%s", msg);
1479 } else {
1480 // If we are not logging, do not bother to look for a second offense.
1481 break;
1482 }
1483 }
1484 }
1485 if (bad_strict_static != nullptr) {
1486 throw_strict_static_exception(bad_strict_static, "is unset after initialization of", THREAD);
1487 }
1488 }
1489 }
1490
1491 // Step 9
1492 if (!HAS_PENDING_EXCEPTION) {
1493 set_initialization_state_and_notify(fully_initialized, CHECK);
1494 DEBUG_ONLY(vtable().verify(tty, true);)
1495 CompilationPolicy::replay_training_at_init(this, THREAD);
1496 }
1497 else {
1498 // Step 10 and 11
1499 Handle e(THREAD, PENDING_EXCEPTION);
1500 CLEAR_PENDING_EXCEPTION;
1501 // JVMTI has already reported the pending exception
1502 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1503 JvmtiExport::clear_detected_exception(jt);
1504 {
1505 EXCEPTION_MARK;
1506 add_initialization_error(THREAD, e);
1507 set_initialization_state_and_notify(initialization_error, THREAD);
1508 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1522 }
1523 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1524 }
1525
1526
1527 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1528 Handle h_init_lock(THREAD, init_lock());
1529 if (h_init_lock() != nullptr) {
1530 ObjectLocker ol(h_init_lock, THREAD);
1531 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1532 set_init_state(state);
1533 fence_and_clear_init_lock();
1534 ol.notify_all(CHECK);
1535 } else {
1536 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1537 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1538 set_init_state(state);
1539 }
1540 }
1541
1542 void InstanceKlass::notify_strict_static_access(int field_index, bool is_writing, TRAPS) {
1543 guarantee(field_index >= 0 && field_index < fields_status()->length(), "valid field index");
1544 DEBUG_ONLY(FieldInfo debugfi = field(field_index));
1545 assert(debugfi.access_flags().is_strict(), "");
1546 assert(debugfi.access_flags().is_static(), "");
1547 FieldStatus& fs = *fields_status()->adr_at(field_index);
1548 LogTarget(Trace, class, init) lt;
1549 if (lt.is_enabled()) {
1550 ResourceMark rm(THREAD);
1551 LogStream ls(lt);
1552 FieldInfo fi = field(field_index);
1553 ls.print("notify %s %s %s%s ",
1554 external_name(), is_writing? "Write" : "Read",
1555 fs.is_strict_static_unset() ? "Unset" : "(set)",
1556 fs.is_strict_static_unread() ? "+Unread" : "");
1557 fi.print(&ls, constants());
1558 }
1559 if (fs.is_strict_static_unset()) {
1560 assert(fs.is_strict_static_unread(), "ClassFileParser resp.");
1561 // If it is not set, there are only two reasonable things we can do here:
1562 // - mark it set if this is putstatic
1563 // - throw an error (Read-Before-Write) if this is getstatic
1564
1565 // The unset state is (or should be) transient, and observable only in one
1566 // thread during the execution of <clinit>. Something is wrong here as this
1567 // should not be possible
1568 guarantee(is_reentrant_initialization(THREAD), "unscoped access to strict static");
1569 if (is_writing) {
1570 // clear the "unset" bit, since the field is actually going to be written
1571 fs.update_strict_static_unset(false);
1572 } else {
1573 // throw an IllegalStateException, since we are reading before writing
1574 // see also InstanceKlass::initialize_impl, Step 8 (at end)
1575 Symbol* bad_strict_static = field(field_index).name(constants());
1576 throw_strict_static_exception(bad_strict_static, "is unset before first read in", CHECK);
1577 }
1578 } else {
1579 // Ensure no write after read for final strict statics
1580 FieldInfo fi = field(field_index);
1581 bool is_final = fi.access_flags().is_final();
1582 if (is_final) {
1583 // no final write after read, so observing a constant freezes it, as if <clinit> ended early
1584 // (maybe we could trust the constant a little earlier, before <clinit> ends)
1585 if (is_writing && !fs.is_strict_static_unread()) {
1586 Symbol* bad_strict_static = fi.name(constants());
1587 throw_strict_static_exception(bad_strict_static, "is set after read (as final) in", CHECK);
1588 } else if (!is_writing && fs.is_strict_static_unread()) {
1589 fs.update_strict_static_unread(false);
1590 }
1591 }
1592 }
1593 }
1594
1595 void InstanceKlass::throw_strict_static_exception(Symbol* field_name, const char* when, TRAPS) {
1596 ResourceMark rm(THREAD);
1597 const char* msg = format_strict_static_message(field_name, when);
1598 THROW_MSG(vmSymbols::java_lang_IllegalStateException(), msg);
1599 }
1600
1601 const char* InstanceKlass::format_strict_static_message(Symbol* field_name, const char* when) {
1602 stringStream ss;
1603 ss.print("Strict static \"%s\" %s %s",
1604 field_name->as_C_string(),
1605 when == nullptr ? "is unset in" : when,
1606 external_name());
1607 return ss.as_string();
1608 }
1609
1610 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1611 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1612 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1613 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1614
1615 DeoptimizationScope deopt_scope;
1616 {
1617 MutexLocker ml(current, Compile_lock);
1618
1619 set_init_state(InstanceKlass::loaded);
1620 // make sure init_state store is already done.
1621 // The compiler reads the hierarchy outside of the Compile_lock.
1622 // Access ordering is used to add to hierarchy.
1623
1624 // Link into hierarchy.
1625 append_to_sibling_list(); // add to superklass/sibling list
1626 process_interfaces(); // handle all "implements" declarations
1627
1628 // Now mark all code that depended on old class hierarchy.
1629 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1840 : vmSymbols::java_lang_IllegalAccessException(), external_name());
1841 }
1842 }
1843
1844 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
1845 // Need load-acquire for lock-free read
1846 if (array_klasses_acquire() == nullptr) {
1847
1848 // Recursively lock array allocation
1849 RecursiveLocker rl(MultiArray_lock, THREAD);
1850
1851 // Check if another thread created the array klass while we were waiting for the lock.
1852 if (array_klasses() == nullptr) {
1853 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
1854 // use 'release' to pair with lock-free load
1855 release_set_array_klasses(k);
1856 }
1857 }
1858
1859 // array_klasses() will always be set at this point
1860 ArrayKlass* ak = array_klasses();
1861 assert(ak != nullptr, "should be set");
1862 return ak->array_klass(n, THREAD);
1863 }
1864
1865 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1866 // Need load-acquire for lock-free read
1867 ArrayKlass* ak = array_klasses_acquire();
1868 if (ak == nullptr) {
1869 return nullptr;
1870 } else {
1871 return ak->array_klass_or_null(n);
1872 }
1873 }
1874
1875 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1876 return array_klass(1, THREAD);
1877 }
1878
1879 ArrayKlass* InstanceKlass::array_klass_or_null() {
1880 return array_klass_or_null(1);
1881 }
1882
1883 static int call_class_initializer_counter = 0; // for debugging
1884
1885 Method* InstanceKlass::class_initializer() const {
1886 Method* clinit = find_method(
1887 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1888 if (clinit != nullptr && clinit->is_class_initializer()) {
1889 return clinit;
1890 }
1891 return nullptr;
1892 }
1893
1894 void InstanceKlass::call_class_initializer(TRAPS) {
1895 if (ReplayCompiles &&
1896 (ReplaySuppressInitializers == 1 ||
1897 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1898 // Hide the existence of the initializer for the purpose of replaying the compile
1899 return;
1900 }
1901
1902 #if INCLUDE_CDS
1903 // This is needed to ensure the consistency of the archived heap objects.
1904 if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
1905 AOTClassInitializer::call_runtime_setup(THREAD, this);
1906 return;
1907 } else if (has_archived_enum_objs()) {
1908 assert(in_aot_cache(), "must be");
1977
1978 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1979 InterpreterOopMap* entry_for) {
1980 // Lazily create the _oop_map_cache at first request.
1981 // Load_acquire is needed to safely get instance published with CAS by another thread.
1982 OopMapCache* oop_map_cache = AtomicAccess::load_acquire(&_oop_map_cache);
1983 if (oop_map_cache == nullptr) {
1984 // Try to install new instance atomically.
1985 oop_map_cache = new OopMapCache();
1986 OopMapCache* other = AtomicAccess::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
1987 if (other != nullptr) {
1988 // Someone else managed to install before us, ditch local copy and use the existing one.
1989 delete oop_map_cache;
1990 oop_map_cache = other;
1991 }
1992 }
1993 // _oop_map_cache is constant after init; lookup below does its own locking.
1994 oop_map_cache->lookup(method, bci, entry_for);
1995 }
1996
1997
1998 FieldInfo InstanceKlass::field(int index) const {
1999 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2000 if (fs.index() == index) {
2001 return fs.to_FieldInfo();
2002 }
2003 }
2004 fatal("Field not found");
2005 return FieldInfo();
2006 }
2007
2008 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
2009 JavaFieldStream fs(this);
2010 if (fs.lookup(name, sig)) {
2011 assert(fs.name() == name, "name must match");
2012 assert(fs.signature() == sig, "signature must match");
2013 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2014 return true;
2015 }
2016 return false;
2057
2058 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
2059 // search order according to newest JVM spec (5.4.3.2, p.167).
2060 // 1) search for field in current klass
2061 if (find_local_field(name, sig, fd)) {
2062 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
2063 }
2064 // 2) search for field recursively in direct superinterfaces
2065 if (is_static) {
2066 Klass* intf = find_interface_field(name, sig, fd);
2067 if (intf != nullptr) return intf;
2068 }
2069 // 3) apply field lookup recursively if superclass exists
2070 { InstanceKlass* supr = super();
2071 if (supr != nullptr) return supr->find_field(name, sig, is_static, fd);
2072 }
2073 // 4) otherwise field lookup fails
2074 return nullptr;
2075 }
2076
2077 bool InstanceKlass::contains_field_offset(int offset) {
2078 if (this->is_inline_klass()) {
2079 InlineKlass* vk = InlineKlass::cast(this);
2080 return offset >= vk->payload_offset() && offset < (vk->payload_offset() + vk->payload_size_in_bytes());
2081 } else {
2082 fieldDescriptor fd;
2083 return find_field_from_offset(offset, false, &fd);
2084 }
2085 }
2086
2087 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2088 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2089 if (fs.offset() == offset) {
2090 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2091 if (fd->is_static() == is_static) return true;
2092 }
2093 }
2094 return false;
2095 }
2096
2097
2098 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2099 const InstanceKlass* klass = this;
2100 while (klass != nullptr) {
2101 if (klass->find_local_field_from_offset(offset, is_static, fd)) {
2102 return true;
2103 }
2104 klass = klass->super();
2105 }
2449 }
2450
2451 // uncached_lookup_method searches both the local class methods array and all
2452 // superclasses methods arrays, skipping any overpass methods in superclasses,
2453 // and possibly skipping private methods.
2454 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2455 const Symbol* signature,
2456 OverpassLookupMode overpass_mode,
2457 PrivateLookupMode private_mode) const {
2458 OverpassLookupMode overpass_local_mode = overpass_mode;
2459 const InstanceKlass* klass = this;
2460 while (klass != nullptr) {
2461 Method* const method = klass->find_method_impl(name,
2462 signature,
2463 overpass_local_mode,
2464 StaticLookupMode::find,
2465 private_mode);
2466 if (method != nullptr) {
2467 return method;
2468 }
2469 if (name == vmSymbols::object_initializer_name()) {
2470 break; // <init> is never inherited
2471 }
2472 klass = klass->super();
2473 overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses
2474 }
2475 return nullptr;
2476 }
2477
2478 #ifdef ASSERT
2479 // search through class hierarchy and return true if this class or
2480 // one of the superclasses was redefined
2481 bool InstanceKlass::has_redefined_this_or_super() const {
2482 const InstanceKlass* klass = this;
2483 while (klass != nullptr) {
2484 if (klass->has_been_redefined()) {
2485 return true;
2486 }
2487 klass = klass->super();
2488 }
2489 return false;
2490 }
2491 #endif
2864 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2865
2866 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2867 / itableOffsetEntry::size();
2868
2869 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2870 if (ioe->interface_klass() != nullptr) {
2871 it->push(ioe->interface_klass_addr());
2872 itableMethodEntry* ime = ioe->first_method_entry(this);
2873 int n = klassItable::method_count_for_interface(ioe->interface_klass());
2874 for (int index = 0; index < n; index ++) {
2875 it->push(ime[index].method_addr());
2876 }
2877 }
2878 }
2879 }
2880
2881 it->push(&_nest_host);
2882 it->push(&_nest_members);
2883 it->push(&_permitted_subclasses);
2884 it->push(&_loadable_descriptors);
2885 it->push(&_record_components);
2886 it->push(&_inline_layout_info_array, MetaspaceClosure::_writable);
2887 }
2888
2889 #if INCLUDE_CDS
2890 void InstanceKlass::remove_unshareable_info() {
2891
2892 if (is_linked()) {
2893 assert(can_be_verified_at_dumptime(), "must be");
2894 // Remember this so we can avoid walking the hierarchy at runtime.
2895 set_verified_at_dump_time();
2896 }
2897
2898 _misc_flags.set_has_init_deps_processed(false);
2899
2900 Klass::remove_unshareable_info();
2901
2902 if (SystemDictionaryShared::has_class_failed_verification(this)) {
2903 // Classes are attempted to link during dumping and may fail,
2904 // but these classes are still in the dictionary and class list in CLD.
2905 // If the class has failed verification, there is nothing else to remove.
2906 return;
2914
2915 { // Otherwise this needs to take out the Compile_lock.
2916 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2917 init_implementor();
2918 }
2919
2920 // Call remove_unshareable_info() on other objects that belong to this class, except
2921 // for constants()->remove_unshareable_info(), which is called in a separate pass in
2922 // ArchiveBuilder::make_klasses_shareable(),
2923
2924 for (int i = 0; i < methods()->length(); i++) {
2925 Method* m = methods()->at(i);
2926 m->remove_unshareable_info();
2927 }
2928
2929 // do array classes also.
2930 if (array_klasses() != nullptr) {
2931 array_klasses()->remove_unshareable_info();
2932 }
2933
2934 // These are not allocated from metaspace. They are safe to set to nullptr.
2935 _source_debug_extension = nullptr;
2936 _dep_context = nullptr;
2937 _osr_nmethods_head = nullptr;
2938 #if INCLUDE_JVMTI
2939 _breakpoints = nullptr;
2940 _previous_versions = nullptr;
2941 _cached_class_file = nullptr;
2942 _jvmti_cached_class_field_map = nullptr;
2943 #endif
2944
2945 _init_thread = nullptr;
2946 _methods_jmethod_ids = nullptr;
2947 _jni_ids = nullptr;
2948 _oop_map_cache = nullptr;
2949 if (CDSConfig::is_dumping_method_handles() && HeapShared::is_lambda_proxy_klass(this)) {
2950 // keep _nest_host
2951 } else {
2952 // clear _nest_host to ensure re-load at runtime
2953 _nest_host = nullptr;
2954 }
3005 void InstanceKlass::compute_has_loops_flag_for_methods() {
3006 Array<Method*>* methods = this->methods();
3007 for (int index = 0; index < methods->length(); ++index) {
3008 Method* m = methods->at(index);
3009 if (!m->is_overpass()) { // work around JDK-8305771
3010 m->compute_has_loops_flag();
3011 }
3012 }
3013 }
3014
3015 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
3016 PackageEntry* pkg_entry, TRAPS) {
3017 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
3018 // before the InstanceKlass is added to the SystemDictionary. Make
3019 // sure the current state is <loaded.
3020 assert(!is_loaded(), "invalid init state");
3021 assert(!shared_loading_failed(), "Must not try to load failed class again");
3022 set_package(loader_data, pkg_entry, CHECK);
3023 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
3024
3025 if (is_inline_klass()) {
3026 InlineKlass::cast(this)->initialize_calling_convention(CHECK);
3027 }
3028
3029 Array<Method*>* methods = this->methods();
3030 int num_methods = methods->length();
3031 for (int index = 0; index < num_methods; ++index) {
3032 methods->at(index)->restore_unshareable_info(CHECK);
3033 }
3034 #if INCLUDE_JVMTI
3035 if (JvmtiExport::has_redefined_a_class()) {
3036 // Reinitialize vtable because RedefineClasses may have changed some
3037 // entries in this vtable for super classes so the CDS vtable might
3038 // point to old or obsolete entries. RedefineClasses doesn't fix up
3039 // vtables in the shared system dictionary, only the main one.
3040 // It also redefines the itable too so fix that too.
3041 // First fix any default methods that point to a super class that may
3042 // have been redefined.
3043 bool trace_name_printed = false;
3044 adjust_default_methods(&trace_name_printed);
3045 if (verified_at_dump_time()) {
3046 // Initialize vtable and itable for classes which can be verified at dump time.
3047 // Unlinked classes such as old classes with major version < 50 cannot be verified
3048 // at dump time.
3049 vtable().initialize_vtable();
3050 itable().initialize_itable();
3051 }
3052 }
3053 #endif // INCLUDE_JVMTI
3054
3055 // restore constant pool resolved references
3056 constants()->restore_unshareable_info(CHECK);
3057
3058 if (array_klasses() != nullptr) {
3059 // To get a consistent list of classes we need MultiArray_lock to ensure
3060 // array classes aren't observed while they are being restored.
3061 RecursiveLocker rl(MultiArray_lock, THREAD);
3062 assert(this == ObjArrayKlass::cast(array_klasses())->bottom_klass(), "sanity");
3063 // Array classes have null protection domain.
3064 // --> see ArrayKlass::complete_create_array_klass()
3065 if (class_loader_data() == nullptr) {
3066 ResourceMark rm(THREAD);
3067 log_debug(cds)(" loader_data %s ", loader_data == nullptr ? "nullptr" : "non null");
3068 log_debug(cds)(" this %s array_klasses %s ", this->name()->as_C_string(), array_klasses()->name()->as_C_string());
3069 }
3070 assert(!array_klasses()->is_refined_objArray_klass(), "must be non-refined objarrayklass");
3071 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
3072 }
3073
3074 // Initialize @ValueBased class annotation if not already set in the archived klass.
3075 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
3076 set_is_value_based();
3077 }
3078
3079 DEBUG_ONLY(FieldInfoStream::validate_search_table(_constants, _fieldinfo_stream, _fieldinfo_search_table));
3080 }
3081
3082 bool InstanceKlass::can_be_verified_at_dumptime() const {
3083 if (AOTMetaspace::in_aot_cache(this)) {
3084 // This is a class that was dumped into the base archive, so we know
3085 // it was verified at dump time.
3086 return true;
3087 }
3088
3089 if (CDSConfig::is_preserving_verification_constraints()) {
3090 return true;
3206 constants()->release_C_heap_structures();
3207 }
3208 }
3209
3210 // The constant pool is on stack if any of the methods are executing or
3211 // referenced by handles.
3212 bool InstanceKlass::on_stack() const {
3213 return _constants->on_stack();
3214 }
3215
3216 Symbol* InstanceKlass::source_file_name() const { return _constants->source_file_name(); }
3217 u2 InstanceKlass::source_file_name_index() const { return _constants->source_file_name_index(); }
3218 void InstanceKlass::set_source_file_name_index(u2 sourcefile_index) { _constants->set_source_file_name_index(sourcefile_index); }
3219
3220 // minor and major version numbers of class file
3221 u2 InstanceKlass::minor_version() const { return _constants->minor_version(); }
3222 void InstanceKlass::set_minor_version(u2 minor_version) { _constants->set_minor_version(minor_version); }
3223 u2 InstanceKlass::major_version() const { return _constants->major_version(); }
3224 void InstanceKlass::set_major_version(u2 major_version) { _constants->set_major_version(major_version); }
3225
3226 bool InstanceKlass::supports_inline_types() const {
3227 return major_version() >= Verifier::VALUE_TYPES_MAJOR_VERSION && minor_version() == Verifier::JAVA_PREVIEW_MINOR_VERSION;
3228 }
3229
3230 const InstanceKlass* InstanceKlass::get_klass_version(int version) const {
3231 for (const InstanceKlass* ik = this; ik != nullptr; ik = ik->previous_versions()) {
3232 if (ik->constants()->version() == version) {
3233 return ik;
3234 }
3235 }
3236 return nullptr;
3237 }
3238
3239 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
3240 if (array == nullptr) {
3241 _source_debug_extension = nullptr;
3242 } else {
3243 // Adding one to the attribute length in order to store a null terminator
3244 // character could cause an overflow because the attribute length is
3245 // already coded with an u4 in the classfile, but in practice, it's
3246 // unlikely to happen.
3247 assert((length+1) > length, "Overflow checking");
3248 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
3249 for (int i = 0; i < length; i++) {
3250 sde[i] = array[i];
3251 }
3252 sde[length] = '\0';
3253 _source_debug_extension = sde;
3254 }
3255 }
3256
3257 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); }
3258 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); }
3259 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); }
3260
3261 const char* InstanceKlass::signature_name() const {
3262 return signature_name_of_carrier(JVM_SIGNATURE_CLASS);
3263 }
3264
3265 const char* InstanceKlass::signature_name_of_carrier(char c) const {
3266 // Get the internal name as a c string
3267 const char* src = (const char*) (name()->as_C_string());
3268 const int src_length = (int)strlen(src);
3269
3270 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
3271
3272 // Add L or Q as type indicator
3273 int dest_index = 0;
3274 dest[dest_index++] = c;
3275
3276 // Add the actual class name
3277 for (int src_index = 0; src_index < src_length; ) {
3278 dest[dest_index++] = src[src_index++];
3279 }
3280
3281 if (is_hidden()) { // Replace the last '+' with a '.'.
3282 for (int index = (int)src_length; index > 0; index--) {
3283 if (dest[index] == '+') {
3284 dest[index] = JVM_SIGNATURE_DOT;
3285 break;
3286 }
3287 }
3288 }
3289
3290 // Add the semicolon and the null
3291 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3292 dest[dest_index] = '\0';
3293 return dest;
3294 }
3535 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3536 constantPoolHandle i_cp(THREAD, constants());
3537 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3538 int ioff = iter.inner_class_info_index();
3539 if (ioff != 0) {
3540 // Check to see if the name matches the class we're looking for
3541 // before attempting to find the class.
3542 if (i_cp->klass_name_at_matches(this, ioff)) {
3543 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3544 if (this == inner_klass) {
3545 *ooff = iter.outer_class_info_index();
3546 *noff = iter.inner_name_index();
3547 return true;
3548 }
3549 }
3550 }
3551 }
3552 return false;
3553 }
3554
3555 void InstanceKlass::check_can_be_annotated_with_NullRestricted(InstanceKlass* type, Symbol* container_klass_name, TRAPS) {
3556 assert(type->is_instance_klass(), "Sanity check");
3557 if (type->is_identity_class()) {
3558 ResourceMark rm(THREAD);
3559 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
3560 err_msg("Class %s expects class %s to be a value class, but it is an identity class",
3561 container_klass_name->as_C_string(),
3562 type->external_name()));
3563 }
3564
3565 if (type->is_abstract()) {
3566 ResourceMark rm(THREAD);
3567 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
3568 err_msg("Class %s expects class %s to be concrete value type, but it is an abstract class",
3569 container_klass_name->as_C_string(),
3570 type->external_name()));
3571 }
3572 }
3573
3574 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3575 InstanceKlass* outer_klass = nullptr;
3576 *inner_is_member = false;
3577 int ooff = 0, noff = 0;
3578 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3579 if (has_inner_classes_attr) {
3580 constantPoolHandle i_cp(THREAD, constants());
3581 if (ooff != 0) {
3582 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3583 if (!ok->is_instance_klass()) {
3584 // If the outer class is not an instance klass then it cannot have
3585 // declared any inner classes.
3586 ResourceMark rm(THREAD);
3587 // Names are all known to be < 64k so we know this formatted message is not excessively large.
3588 Exceptions::fthrow(
3589 THREAD_AND_LOCATION,
3590 vmSymbols::java_lang_IncompatibleClassChangeError(),
3591 "%s and %s disagree on InnerClasses attribute",
3592 ok->external_name(),
3593 external_name());
3620 u2 InstanceKlass::compute_modifier_flags() const {
3621 u2 access = access_flags().as_unsigned_short();
3622
3623 // But check if it happens to be member class.
3624 InnerClassesIterator iter(this);
3625 for (; !iter.done(); iter.next()) {
3626 int ioff = iter.inner_class_info_index();
3627 // Inner class attribute can be zero, skip it.
3628 // Strange but true: JVM spec. allows null inner class refs.
3629 if (ioff == 0) continue;
3630
3631 // only look at classes that are already loaded
3632 // since we are looking for the flags for our self.
3633 Symbol* inner_name = constants()->klass_name_at(ioff);
3634 if (name() == inner_name) {
3635 // This is really a member class.
3636 access = iter.inner_access_flags();
3637 break;
3638 }
3639 }
3640 return access;
3641 }
3642
3643 jint InstanceKlass::jvmti_class_status() const {
3644 jint result = 0;
3645
3646 if (is_linked()) {
3647 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3648 }
3649
3650 if (is_initialized()) {
3651 assert(is_linked(), "Class status is not consistent");
3652 result |= JVMTI_CLASS_STATUS_INITIALIZED;
3653 }
3654 if (is_in_error_state()) {
3655 result |= JVMTI_CLASS_STATUS_ERROR;
3656 }
3657 return result;
3658 }
3659
3660 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
3874 }
3875 osr = osr->osr_link();
3876 }
3877
3878 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
3879 if (best != nullptr && best->comp_level() >= comp_level) {
3880 return best;
3881 }
3882 return nullptr;
3883 }
3884
3885 // -----------------------------------------------------------------------------------------------------
3886 // Printing
3887
3888 #define BULLET " - "
3889
3890 static const char* state_names[] = {
3891 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3892 };
3893
3894 static void print_vtable(address self, intptr_t* start, int len, outputStream* st) {
3895 ResourceMark rm;
3896 int* forward_refs = NEW_RESOURCE_ARRAY(int, len);
3897 for (int i = 0; i < len; i++) forward_refs[i] = 0;
3898 for (int i = 0; i < len; i++) {
3899 intptr_t e = start[i];
3900 st->print("%d : " INTPTR_FORMAT, i, e);
3901 if (forward_refs[i] != 0) {
3902 int from = forward_refs[i];
3903 int off = (int) start[from];
3904 st->print(" (offset %d <= [%d])", off, from);
3905 }
3906 if (MetaspaceObj::is_valid((Metadata*)e)) {
3907 st->print(" ");
3908 ((Metadata*)e)->print_value_on(st);
3909 } else if (self != nullptr && e > 0 && e < 0x10000) {
3910 address location = self + e;
3911 int index = (int)((intptr_t*)location - start);
3912 st->print(" (offset %d => [%d])", (int)e, index);
3913 if (index >= 0 && index < len)
3914 forward_refs[index] = i;
3915 }
3916 st->cr();
3917 }
3918 }
3919
3920 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3921 return print_vtable(nullptr, reinterpret_cast<intptr_t*>(start), len, st);
3922 }
3923
3924 template<typename T>
3925 static void print_array_on(outputStream* st, Array<T>* array) {
3926 if (array == nullptr) { st->print_cr("nullptr"); return; }
3927 array->print_value_on(st); st->cr();
3928 if (Verbose || WizardMode) {
3929 for (int i = 0; i < array->length(); i++) {
3930 st->print("%d : ", i); array->at(i)->print_value_on(st); st->cr();
3931 }
3932 }
3933 }
3934
3935 static void print_array_on(outputStream* st, Array<int>* array) {
3936 if (array == nullptr) { st->print_cr("nullptr"); return; }
3937 array->print_value_on(st); st->cr();
3938 if (Verbose || WizardMode) {
3939 for (int i = 0; i < array->length(); i++) {
3940 st->print("%d : %d", i, array->at(i)); st->cr();
3941 }
3942 }
3943 }
3944
3945 const char* InstanceKlass::init_state_name() const {
3946 return state_names[init_state()];
3947 }
3948
3949 void InstanceKlass::print_on(outputStream* st) const {
3950 assert(is_klass(), "must be klass");
3951 Klass::print_on(st);
3952
3953 st->print(BULLET"instance size: %d", size_helper()); st->cr();
3954 st->print(BULLET"klass size: %d", size()); st->cr();
3955 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
3956 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
3957 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
3958 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
3959 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3960 st->print(BULLET"sub: ");
3961 Klass* sub = subklass();
3962 int n;
3963 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3964 if (n < MaxSubklassPrintSize) {
3965 sub->print_value_on(st);
3966 st->print(" ");
3967 }
3968 }
3969 if (n >= MaxSubklassPrintSize) st->print("(%zd more klasses...)", n - MaxSubklassPrintSize);
3970 st->cr();
3971
3972 if (is_interface()) {
3973 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
3974 if (nof_implementors() == 1) {
3975 st->print_cr(BULLET"implementor: ");
3976 st->print(" ");
3977 implementor()->print_value_on(st);
3978 st->cr();
3979 }
3980 }
3981
3982 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3983 st->print(BULLET"methods: "); print_array_on(st, methods());
3984 st->print(BULLET"method ordering: "); print_array_on(st, method_ordering());
3985 if (default_methods() != nullptr) {
3986 st->print(BULLET"default_methods: "); print_array_on(st, default_methods());
3987 }
3988 print_on_maybe_null(st, BULLET"default vtable indices: ", default_vtable_indices());
3989 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
3990 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3991
3992 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr();
3993
3994 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr();
3995 st->print(BULLET"secondary bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap); st->cr();
3996
3997 if (secondary_supers() != nullptr) {
3998 if (Verbose) {
3999 bool is_hashed = (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL);
4000 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length());
4001 for (int i = 0; i < _secondary_supers->length(); i++) {
4002 ResourceMark rm; // for external_name()
4003 Klass* secondary_super = _secondary_supers->at(i);
4004 st->print(BULLET"%2d:", i);
4005 if (is_hashed) {
4006 int home_slot = compute_home_slot(secondary_super, _secondary_supers_bitmap);
4026 print_on_maybe_null(st, BULLET"field type annotations: ", fields_type_annotations());
4027 {
4028 bool have_pv = false;
4029 // previous versions are linked together through the InstanceKlass
4030 for (InstanceKlass* pv_node = previous_versions();
4031 pv_node != nullptr;
4032 pv_node = pv_node->previous_versions()) {
4033 if (!have_pv)
4034 st->print(BULLET"previous version: ");
4035 have_pv = true;
4036 pv_node->constants()->print_value_on(st);
4037 }
4038 if (have_pv) st->cr();
4039 }
4040
4041 print_on_maybe_null(st, BULLET"generic signature: ", generic_signature());
4042 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
4043 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();
4044 print_on_maybe_null(st, BULLET"record components: ", record_components());
4045 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();
4046 st->print(BULLET"loadable descriptors: "); loadable_descriptors()->print_value_on(st); st->cr();
4047 if (java_mirror() != nullptr) {
4048 st->print(BULLET"java mirror: ");
4049 java_mirror()->print_value_on(st);
4050 st->cr();
4051 } else {
4052 st->print_cr(BULLET"java mirror: null");
4053 }
4054 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
4055 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);
4056 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
4057 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(nullptr, start_of_itable(), itable_length(), st);
4058 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
4059
4060 FieldPrinter print_static_field(st);
4061 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
4062 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
4063 FieldPrinter print_nonstatic_field(st);
4064 InstanceKlass* ik = const_cast<InstanceKlass*>(this);
4065 ik->print_nonstatic_fields(&print_nonstatic_field);
4066
4067 st->print(BULLET"non-static oop maps (%d entries): ", nonstatic_oop_map_count());
4068 OopMapBlock* map = start_of_nonstatic_oop_maps();
4069 OopMapBlock* end_map = map + nonstatic_oop_map_count();
4070 while (map < end_map) {
4071 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
4072 map++;
4073 }
4074 st->cr();
4075
4076 if (fieldinfo_search_table() != nullptr) {
4077 st->print_cr(BULLET"---- field info search table:");
4078 FieldInfoStream::print_search_table(st, _constants, _fieldinfo_stream, _fieldinfo_search_table);
4079 }
4080 }
4081
4082 void InstanceKlass::print_value_on(outputStream* st) const {
4083 assert(is_klass(), "must be klass");
4084 if (Verbose || WizardMode) access_flags().print_on(st);
4085 name()->print_value_on(st);
4086 }
4087
4088 void FieldPrinter::do_field(fieldDescriptor* fd) {
4089 for (int i = 0; i < _indent; i++) _st->print(" ");
4090 _st->print(BULLET);
4091 if (_obj == nullptr) {
4092 fd->print_on(_st, _base_offset);
4093 _st->cr();
4094 } else {
4095 fd->print_on_for(_st, _obj, _indent, _base_offset);
4096 if (!fd->field_flags().is_flat()) _st->cr();
4097 }
4098 }
4099
4100
4101 void InstanceKlass::oop_print_on(oop obj, outputStream* st, int indent, int base_offset) {
4102 Klass::oop_print_on(obj, st);
4103
4104 if (this == vmClasses::String_klass()) {
4105 typeArrayOop value = java_lang_String::value(obj);
4106 juint length = java_lang_String::length(obj);
4107 if (value != nullptr &&
4108 value->is_typeArray() &&
4109 length <= (juint) value->length()) {
4110 st->print(BULLET"string: ");
4111 java_lang_String::print(obj, st);
4112 st->cr();
4113 }
4114 }
4115
4116 st->print_cr(BULLET"---- fields (total size %zu words):", oop_size(obj));
4117 FieldPrinter print_field(st, obj, indent, base_offset);
4118 print_nonstatic_fields(&print_field);
4119
4120 if (this == vmClasses::Class_klass()) {
4121 st->print(BULLET"signature: ");
4122 java_lang_Class::print_signature(obj, st);
4123 st->cr();
4124 Klass* real_klass = java_lang_Class::as_Klass(obj);
4125 if (real_klass != nullptr && real_klass->is_instance_klass()) {
4126 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj));
4127 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
4128 }
4129 } else if (this == vmClasses::MethodType_klass()) {
4130 st->print(BULLET"signature: ");
4131 java_lang_invoke_MethodType::print_signature(obj, st);
4132 st->cr();
4133 }
4134 }
4135
4136 #ifndef PRODUCT
4137
|