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 }
901 #ifdef ASSERT
902 {
903 Handle h_init_lock(THREAD, init_lock());
904 ObjectLocker ol(h_init_lock, THREAD);
905 assert(!is_initialized(), "sanity");
906 assert(!is_being_initialized(), "sanity");
907 assert(!is_in_error_state(), "sanity");
908 }
909 #endif
910
911 set_init_thread(THREAD);
912 set_initialization_state_and_notify(fully_initialized, CHECK);
913 }
914 #endif
915
916 bool InstanceKlass::verify_code(TRAPS) {
917 // 1) Verify the bytecodes
918 return Verifier::verify(this, should_verify_class(), THREAD);
919 }
920
921 void InstanceKlass::link_class(TRAPS) {
922 assert(is_loaded(), "must be loaded");
923 if (!is_linked()) {
924 link_class_impl(CHECK);
925 }
926 }
927
928 // Called to verify that a class can link during initialization, without
929 // throwing a VerifyError.
930 bool InstanceKlass::link_class_or_fail(TRAPS) {
931 assert(is_loaded(), "must be loaded");
932 if (!is_linked()) {
933 link_class_impl(CHECK_false);
934 }
935 return is_linked();
936 }
937
938 bool InstanceKlass::link_class_impl(TRAPS) {
939 if (CDSConfig::is_dumping_static_archive() && SystemDictionaryShared::has_class_failed_verification(this)) {
940 // This is for CDS static dump only -- we use the in_error_state to indicate that
971 THREAD_AND_LOCATION,
972 vmSymbols::java_lang_IncompatibleClassChangeError(),
973 "class %s has interface %s as super class",
974 external_name(),
975 super_klass->external_name()
976 );
977 return false;
978 }
979
980 super_klass->link_class_impl(CHECK_false);
981 }
982
983 // link all interfaces implemented by this class before linking this class
984 Array<InstanceKlass*>* interfaces = local_interfaces();
985 int num_interfaces = interfaces->length();
986 for (int index = 0; index < num_interfaces; index++) {
987 InstanceKlass* interk = interfaces->at(index);
988 interk->link_class_impl(CHECK_false);
989 }
990
991 // in case the class is linked in the process of linking its superclasses
992 if (is_linked()) {
993 return true;
994 }
995
996 // trace only the link time for this klass that includes
997 // the verification time
998 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
999 ClassLoader::perf_class_link_selftime(),
1000 ClassLoader::perf_classes_linked(),
1001 jt->get_thread_stat()->perf_recursion_counts_addr(),
1002 jt->get_thread_stat()->perf_timers_addr(),
1003 PerfClassTraceTime::CLASS_LINK);
1004
1005 // verification & rewriting
1006 {
1007 HandleMark hm(THREAD);
1008 Handle h_init_lock(THREAD, init_lock());
1009 ObjectLocker ol(h_init_lock, CHECK_PREEMPTABLE_false);
1010 // Don't allow preemption if we link/initialize classes below,
1294 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1295 ss.as_string(), cause);
1296 }
1297 } else {
1298
1299 // Step 6
1300 set_init_state(being_initialized);
1301 set_init_thread(jt);
1302 if (debug_logging_enabled) {
1303 ResourceMark rm(jt);
1304 log_debug(class, init)("Thread \"%s\" is initializing %s",
1305 jt->name(), external_name());
1306 }
1307 }
1308 }
1309
1310 // Block preemption once we are the initializer thread. Unmounting now
1311 // would complicate the reentrant case (identity is platform thread).
1312 NoPreemptMark npm(THREAD);
1313
1314 // Step 7
1315 // Next, if C is a class rather than an interface, initialize it's super class and super
1316 // interfaces.
1317 if (!is_interface()) {
1318 Klass* super_klass = super();
1319 if (super_klass != nullptr && super_klass->should_be_initialized()) {
1320 super_klass->initialize(THREAD);
1321 }
1322 // If C implements any interface that declares a non-static, concrete method,
1323 // the initialization of C triggers initialization of its super interfaces.
1324 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1325 // having a superinterface that declares, non-static, concrete methods
1326 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1327 initialize_super_interfaces(THREAD);
1328 }
1329
1330 // If any exceptions, complete abruptly, throwing the same exception as above.
1331 if (HAS_PENDING_EXCEPTION) {
1332 Handle e(THREAD, PENDING_EXCEPTION);
1333 CLEAR_PENDING_EXCEPTION;
1334 {
1335 EXCEPTION_MARK;
1336 add_initialization_error(THREAD, e);
1337 // Locks object, set state, and notify all waiting threads
1338 set_initialization_state_and_notify(initialization_error, THREAD);
1339 CLEAR_PENDING_EXCEPTION;
1340 }
1341 DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1342 THROW_OOP(e());
1343 }
1344 }
1345
1346
1347 // Step 8
1348 {
1349 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1350 if (class_initializer() != nullptr) {
1351 // Timer includes any side effects of class initialization (resolution,
1352 // etc), but not recursive entry into call_class_initializer().
1353 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1354 ClassLoader::perf_class_init_selftime(),
1355 ClassLoader::perf_classes_inited(),
1356 jt->get_thread_stat()->perf_recursion_counts_addr(),
1357 jt->get_thread_stat()->perf_timers_addr(),
1358 PerfClassTraceTime::CLASS_CLINIT);
1359 call_class_initializer(THREAD);
1360 } else {
1361 // The elapsed time is so small it's not worth counting.
1362 if (UsePerfData) {
1363 ClassLoader::perf_classes_inited()->inc();
1364 }
1365 call_class_initializer(THREAD);
1366 }
1367 }
1368
1369 // Step 9
1370 if (!HAS_PENDING_EXCEPTION) {
1371 set_initialization_state_and_notify(fully_initialized, CHECK);
1372 DEBUG_ONLY(vtable().verify(tty, true);)
1373 CompilationPolicy::replay_training_at_init(this, THREAD);
1374 }
1375 else {
1376 // Step 10 and 11
1377 Handle e(THREAD, PENDING_EXCEPTION);
1378 CLEAR_PENDING_EXCEPTION;
1379 // JVMTI has already reported the pending exception
1380 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1381 JvmtiExport::clear_detected_exception(jt);
1382 {
1383 EXCEPTION_MARK;
1384 add_initialization_error(THREAD, e);
1385 set_initialization_state_and_notify(initialization_error, THREAD);
1386 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1400 }
1401 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1402 }
1403
1404
1405 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1406 Handle h_init_lock(THREAD, init_lock());
1407 if (h_init_lock() != nullptr) {
1408 ObjectLocker ol(h_init_lock, THREAD);
1409 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1410 set_init_state(state);
1411 fence_and_clear_init_lock();
1412 ol.notify_all(CHECK);
1413 } else {
1414 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1415 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1416 set_init_state(state);
1417 }
1418 }
1419
1420 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1421 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1422 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1423 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1424
1425 DeoptimizationScope deopt_scope;
1426 {
1427 MutexLocker ml(current, Compile_lock);
1428
1429 set_init_state(InstanceKlass::loaded);
1430 // make sure init_state store is already done.
1431 // The compiler reads the hierarchy outside of the Compile_lock.
1432 // Access ordering is used to add to hierarchy.
1433
1434 // Link into hierarchy.
1435 append_to_sibling_list(); // add to superklass/sibling list
1436 process_interfaces(); // handle all "implements" declarations
1437
1438 // Now mark all code that depended on old class hierarchy.
1439 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1650 : vmSymbols::java_lang_IllegalAccessException(), external_name());
1651 }
1652 }
1653
1654 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
1655 // Need load-acquire for lock-free read
1656 if (array_klasses_acquire() == nullptr) {
1657
1658 // Recursively lock array allocation
1659 RecursiveLocker rl(MultiArray_lock, THREAD);
1660
1661 // Check if another thread created the array klass while we were waiting for the lock.
1662 if (array_klasses() == nullptr) {
1663 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
1664 // use 'release' to pair with lock-free load
1665 release_set_array_klasses(k);
1666 }
1667 }
1668
1669 // array_klasses() will always be set at this point
1670 ObjArrayKlass* ak = array_klasses();
1671 assert(ak != nullptr, "should be set");
1672 return ak->array_klass(n, THREAD);
1673 }
1674
1675 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1676 // Need load-acquire for lock-free read
1677 ObjArrayKlass* oak = array_klasses_acquire();
1678 if (oak == nullptr) {
1679 return nullptr;
1680 } else {
1681 return oak->array_klass_or_null(n);
1682 }
1683 }
1684
1685 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1686 return array_klass(1, THREAD);
1687 }
1688
1689 ArrayKlass* InstanceKlass::array_klass_or_null() {
1690 return array_klass_or_null(1);
1691 }
1692
1693 static int call_class_initializer_counter = 0; // for debugging
1694
1695 Method* InstanceKlass::class_initializer() const {
1696 Method* clinit = find_method(
1697 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1698 if (clinit != nullptr && clinit->has_valid_initializer_flags()) {
1699 return clinit;
1700 }
1701 return nullptr;
1702 }
1703
1704 void InstanceKlass::call_class_initializer(TRAPS) {
1705 if (ReplayCompiles &&
1706 (ReplaySuppressInitializers == 1 ||
1707 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1708 // Hide the existence of the initializer for the purpose of replaying the compile
1709 return;
1710 }
1711
1712 #if INCLUDE_CDS
1713 // This is needed to ensure the consistency of the archived heap objects.
1714 if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
1715 AOTClassInitializer::call_runtime_setup(THREAD, this);
1716 return;
1717 } else if (has_archived_enum_objs()) {
1718 assert(in_aot_cache(), "must be");
1787
1788 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1789 InterpreterOopMap* entry_for) {
1790 // Lazily create the _oop_map_cache at first request.
1791 // Load_acquire is needed to safely get instance published with CAS by another thread.
1792 OopMapCache* oop_map_cache = AtomicAccess::load_acquire(&_oop_map_cache);
1793 if (oop_map_cache == nullptr) {
1794 // Try to install new instance atomically.
1795 oop_map_cache = new OopMapCache();
1796 OopMapCache* other = AtomicAccess::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
1797 if (other != nullptr) {
1798 // Someone else managed to install before us, ditch local copy and use the existing one.
1799 delete oop_map_cache;
1800 oop_map_cache = other;
1801 }
1802 }
1803 // _oop_map_cache is constant after init; lookup below does its own locking.
1804 oop_map_cache->lookup(method, bci, entry_for);
1805 }
1806
1807 bool InstanceKlass::contains_field_offset(int offset) {
1808 fieldDescriptor fd;
1809 return find_field_from_offset(offset, false, &fd);
1810 }
1811
1812 FieldInfo InstanceKlass::field(int index) const {
1813 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
1814 if (fs.index() == index) {
1815 return fs.to_FieldInfo();
1816 }
1817 }
1818 fatal("Field not found");
1819 return FieldInfo();
1820 }
1821
1822 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1823 JavaFieldStream fs(this);
1824 if (fs.lookup(name, sig)) {
1825 assert(fs.name() == name, "name must match");
1826 assert(fs.signature() == sig, "signature must match");
1827 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
1828 return true;
1829 }
1830 return false;
1871
1872 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1873 // search order according to newest JVM spec (5.4.3.2, p.167).
1874 // 1) search for field in current klass
1875 if (find_local_field(name, sig, fd)) {
1876 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1877 }
1878 // 2) search for field recursively in direct superinterfaces
1879 if (is_static) {
1880 Klass* intf = find_interface_field(name, sig, fd);
1881 if (intf != nullptr) return intf;
1882 }
1883 // 3) apply field lookup recursively if superclass exists
1884 { InstanceKlass* supr = super();
1885 if (supr != nullptr) return supr->find_field(name, sig, is_static, fd);
1886 }
1887 // 4) otherwise field lookup fails
1888 return nullptr;
1889 }
1890
1891
1892 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1893 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1894 if (fs.offset() == offset) {
1895 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
1896 if (fd->is_static() == is_static) return true;
1897 }
1898 }
1899 return false;
1900 }
1901
1902
1903 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1904 const InstanceKlass* klass = this;
1905 while (klass != nullptr) {
1906 if (klass->find_local_field_from_offset(offset, is_static, fd)) {
1907 return true;
1908 }
1909 klass = klass->super();
1910 }
2254 }
2255
2256 // uncached_lookup_method searches both the local class methods array and all
2257 // superclasses methods arrays, skipping any overpass methods in superclasses,
2258 // and possibly skipping private methods.
2259 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2260 const Symbol* signature,
2261 OverpassLookupMode overpass_mode,
2262 PrivateLookupMode private_mode) const {
2263 OverpassLookupMode overpass_local_mode = overpass_mode;
2264 const InstanceKlass* klass = this;
2265 while (klass != nullptr) {
2266 Method* const method = klass->find_method_impl(name,
2267 signature,
2268 overpass_local_mode,
2269 StaticLookupMode::find,
2270 private_mode);
2271 if (method != nullptr) {
2272 return method;
2273 }
2274 klass = klass->super();
2275 overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses
2276 }
2277 return nullptr;
2278 }
2279
2280 #ifdef ASSERT
2281 // search through class hierarchy and return true if this class or
2282 // one of the superclasses was redefined
2283 bool InstanceKlass::has_redefined_this_or_super() const {
2284 const InstanceKlass* klass = this;
2285 while (klass != nullptr) {
2286 if (klass->has_been_redefined()) {
2287 return true;
2288 }
2289 klass = klass->super();
2290 }
2291 return false;
2292 }
2293 #endif
2666 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2667
2668 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2669 / itableOffsetEntry::size();
2670
2671 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2672 if (ioe->interface_klass() != nullptr) {
2673 it->push(ioe->interface_klass_addr());
2674 itableMethodEntry* ime = ioe->first_method_entry(this);
2675 int n = klassItable::method_count_for_interface(ioe->interface_klass());
2676 for (int index = 0; index < n; index ++) {
2677 it->push(ime[index].method_addr());
2678 }
2679 }
2680 }
2681 }
2682
2683 it->push(&_nest_host);
2684 it->push(&_nest_members);
2685 it->push(&_permitted_subclasses);
2686 it->push(&_record_components);
2687 }
2688
2689 #if INCLUDE_CDS
2690 void InstanceKlass::remove_unshareable_info() {
2691
2692 if (is_linked()) {
2693 assert(can_be_verified_at_dumptime(), "must be");
2694 // Remember this so we can avoid walking the hierarchy at runtime.
2695 set_verified_at_dump_time();
2696 }
2697
2698 _misc_flags.set_has_init_deps_processed(false);
2699
2700 Klass::remove_unshareable_info();
2701
2702 if (SystemDictionaryShared::has_class_failed_verification(this)) {
2703 // Classes are attempted to link during dumping and may fail,
2704 // but these classes are still in the dictionary and class list in CLD.
2705 // If the class has failed verification, there is nothing else to remove.
2706 return;
2714
2715 { // Otherwise this needs to take out the Compile_lock.
2716 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2717 init_implementor();
2718 }
2719
2720 // Call remove_unshareable_info() on other objects that belong to this class, except
2721 // for constants()->remove_unshareable_info(), which is called in a separate pass in
2722 // ArchiveBuilder::make_klasses_shareable(),
2723
2724 for (int i = 0; i < methods()->length(); i++) {
2725 Method* m = methods()->at(i);
2726 m->remove_unshareable_info();
2727 }
2728
2729 // do array classes also.
2730 if (array_klasses() != nullptr) {
2731 array_klasses()->remove_unshareable_info();
2732 }
2733
2734 // These are not allocated from metaspace. They are safe to set to null.
2735 _source_debug_extension = nullptr;
2736 _dep_context = nullptr;
2737 _osr_nmethods_head = nullptr;
2738 #if INCLUDE_JVMTI
2739 _breakpoints = nullptr;
2740 _previous_versions = nullptr;
2741 _cached_class_file = nullptr;
2742 _jvmti_cached_class_field_map = nullptr;
2743 #endif
2744
2745 _init_thread = nullptr;
2746 _methods_jmethod_ids = nullptr;
2747 _jni_ids = nullptr;
2748 _oop_map_cache = nullptr;
2749 if (CDSConfig::is_dumping_method_handles() && HeapShared::is_lambda_proxy_klass(this)) {
2750 // keep _nest_host
2751 } else {
2752 // clear _nest_host to ensure re-load at runtime
2753 _nest_host = nullptr;
2754 }
2805 void InstanceKlass::compute_has_loops_flag_for_methods() {
2806 Array<Method*>* methods = this->methods();
2807 for (int index = 0; index < methods->length(); ++index) {
2808 Method* m = methods->at(index);
2809 if (!m->is_overpass()) { // work around JDK-8305771
2810 m->compute_has_loops_flag();
2811 }
2812 }
2813 }
2814
2815 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
2816 PackageEntry* pkg_entry, TRAPS) {
2817 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
2818 // before the InstanceKlass is added to the SystemDictionary. Make
2819 // sure the current state is <loaded.
2820 assert(!is_loaded(), "invalid init state");
2821 assert(!shared_loading_failed(), "Must not try to load failed class again");
2822 set_package(loader_data, pkg_entry, CHECK);
2823 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2824
2825 Array<Method*>* methods = this->methods();
2826 int num_methods = methods->length();
2827 for (int index = 0; index < num_methods; ++index) {
2828 methods->at(index)->restore_unshareable_info(CHECK);
2829 }
2830 #if INCLUDE_JVMTI
2831 if (JvmtiExport::has_redefined_a_class()) {
2832 // Reinitialize vtable because RedefineClasses may have changed some
2833 // entries in this vtable for super classes so the CDS vtable might
2834 // point to old or obsolete entries. RedefineClasses doesn't fix up
2835 // vtables in the shared system dictionary, only the main one.
2836 // It also redefines the itable too so fix that too.
2837 // First fix any default methods that point to a super class that may
2838 // have been redefined.
2839 bool trace_name_printed = false;
2840 adjust_default_methods(&trace_name_printed);
2841 if (verified_at_dump_time()) {
2842 // Initialize vtable and itable for classes which can be verified at dump time.
2843 // Unlinked classes such as old classes with major version < 50 cannot be verified
2844 // at dump time.
2845 vtable().initialize_vtable();
2846 itable().initialize_itable();
2847 }
2848 }
2849 #endif // INCLUDE_JVMTI
2850
2851 // restore constant pool resolved references
2852 constants()->restore_unshareable_info(CHECK);
2853
2854 if (array_klasses() != nullptr) {
2855 // To get a consistent list of classes we need MultiArray_lock to ensure
2856 // array classes aren't observed while they are being restored.
2857 RecursiveLocker rl(MultiArray_lock, THREAD);
2858 assert(this == array_klasses()->bottom_klass(), "sanity");
2859 // Array classes have null protection domain.
2860 // --> see ArrayKlass::complete_create_array_klass()
2861 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
2862 }
2863
2864 // Initialize @ValueBased class annotation if not already set in the archived klass.
2865 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
2866 set_is_value_based();
2867 }
2868
2869 DEBUG_ONLY(FieldInfoStream::validate_search_table(_constants, _fieldinfo_stream, _fieldinfo_search_table));
2870 }
2871
2872 bool InstanceKlass::can_be_verified_at_dumptime() const {
2873 if (AOTMetaspace::in_aot_cache(this)) {
2874 // This is a class that was dumped into the base archive, so we know
2875 // it was verified at dump time.
2876 return true;
2877 }
2878
2879 if (CDSConfig::is_preserving_verification_constraints()) {
2880 return true;
2996 constants()->release_C_heap_structures();
2997 }
2998 }
2999
3000 // The constant pool is on stack if any of the methods are executing or
3001 // referenced by handles.
3002 bool InstanceKlass::on_stack() const {
3003 return _constants->on_stack();
3004 }
3005
3006 Symbol* InstanceKlass::source_file_name() const { return _constants->source_file_name(); }
3007 u2 InstanceKlass::source_file_name_index() const { return _constants->source_file_name_index(); }
3008 void InstanceKlass::set_source_file_name_index(u2 sourcefile_index) { _constants->set_source_file_name_index(sourcefile_index); }
3009
3010 // minor and major version numbers of class file
3011 u2 InstanceKlass::minor_version() const { return _constants->minor_version(); }
3012 void InstanceKlass::set_minor_version(u2 minor_version) { _constants->set_minor_version(minor_version); }
3013 u2 InstanceKlass::major_version() const { return _constants->major_version(); }
3014 void InstanceKlass::set_major_version(u2 major_version) { _constants->set_major_version(major_version); }
3015
3016 const InstanceKlass* InstanceKlass::get_klass_version(int version) const {
3017 for (const InstanceKlass* ik = this; ik != nullptr; ik = ik->previous_versions()) {
3018 if (ik->constants()->version() == version) {
3019 return ik;
3020 }
3021 }
3022 return nullptr;
3023 }
3024
3025 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
3026 if (array == nullptr) {
3027 _source_debug_extension = nullptr;
3028 } else {
3029 // Adding one to the attribute length in order to store a null terminator
3030 // character could cause an overflow because the attribute length is
3031 // already coded with an u4 in the classfile, but in practice, it's
3032 // unlikely to happen.
3033 assert((length+1) > length, "Overflow checking");
3034 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
3035 for (int i = 0; i < length; i++) {
3036 sde[i] = array[i];
3037 }
3038 sde[length] = '\0';
3039 _source_debug_extension = sde;
3040 }
3041 }
3042
3043 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); }
3044 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); }
3045 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); }
3046
3047 const char* InstanceKlass::signature_name() const {
3048
3049 // Get the internal name as a c string
3050 const char* src = (const char*) (name()->as_C_string());
3051 const int src_length = (int)strlen(src);
3052
3053 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
3054
3055 // Add L as type indicator
3056 int dest_index = 0;
3057 dest[dest_index++] = JVM_SIGNATURE_CLASS;
3058
3059 // Add the actual class name
3060 for (int src_index = 0; src_index < src_length; ) {
3061 dest[dest_index++] = src[src_index++];
3062 }
3063
3064 if (is_hidden()) { // Replace the last '+' with a '.'.
3065 for (int index = (int)src_length; index > 0; index--) {
3066 if (dest[index] == '+') {
3067 dest[index] = JVM_SIGNATURE_DOT;
3068 break;
3069 }
3070 }
3071 }
3072
3073 // Add the semicolon and the null
3074 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3075 dest[dest_index] = '\0';
3076 return dest;
3077 }
3318 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3319 constantPoolHandle i_cp(THREAD, constants());
3320 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3321 int ioff = iter.inner_class_info_index();
3322 if (ioff != 0) {
3323 // Check to see if the name matches the class we're looking for
3324 // before attempting to find the class.
3325 if (i_cp->klass_name_at_matches(this, ioff)) {
3326 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3327 if (this == inner_klass) {
3328 *ooff = iter.outer_class_info_index();
3329 *noff = iter.inner_name_index();
3330 return true;
3331 }
3332 }
3333 }
3334 }
3335 return false;
3336 }
3337
3338 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3339 InstanceKlass* outer_klass = nullptr;
3340 *inner_is_member = false;
3341 int ooff = 0, noff = 0;
3342 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3343 if (has_inner_classes_attr) {
3344 constantPoolHandle i_cp(THREAD, constants());
3345 if (ooff != 0) {
3346 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3347 if (!ok->is_instance_klass()) {
3348 // If the outer class is not an instance klass then it cannot have
3349 // declared any inner classes.
3350 ResourceMark rm(THREAD);
3351 // Names are all known to be < 64k so we know this formatted message is not excessively large.
3352 Exceptions::fthrow(
3353 THREAD_AND_LOCATION,
3354 vmSymbols::java_lang_IncompatibleClassChangeError(),
3355 "%s and %s disagree on InnerClasses attribute",
3356 ok->external_name(),
3357 external_name());
3384 u2 InstanceKlass::compute_modifier_flags() const {
3385 u2 access = access_flags().as_unsigned_short();
3386
3387 // But check if it happens to be member class.
3388 InnerClassesIterator iter(this);
3389 for (; !iter.done(); iter.next()) {
3390 int ioff = iter.inner_class_info_index();
3391 // Inner class attribute can be zero, skip it.
3392 // Strange but true: JVM spec. allows null inner class refs.
3393 if (ioff == 0) continue;
3394
3395 // only look at classes that are already loaded
3396 // since we are looking for the flags for our self.
3397 Symbol* inner_name = constants()->klass_name_at(ioff);
3398 if (name() == inner_name) {
3399 // This is really a member class.
3400 access = iter.inner_access_flags();
3401 break;
3402 }
3403 }
3404 // Remember to strip ACC_SUPER bit
3405 return (access & (~JVM_ACC_SUPER));
3406 }
3407
3408 jint InstanceKlass::jvmti_class_status() const {
3409 jint result = 0;
3410
3411 if (is_linked()) {
3412 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3413 }
3414
3415 if (is_initialized()) {
3416 assert(is_linked(), "Class status is not consistent");
3417 result |= JVMTI_CLASS_STATUS_INITIALIZED;
3418 }
3419 if (is_in_error_state()) {
3420 result |= JVMTI_CLASS_STATUS_ERROR;
3421 }
3422 return result;
3423 }
3424
3425 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
3639 }
3640 osr = osr->osr_link();
3641 }
3642
3643 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
3644 if (best != nullptr && best->comp_level() >= comp_level) {
3645 return best;
3646 }
3647 return nullptr;
3648 }
3649
3650 // -----------------------------------------------------------------------------------------------------
3651 // Printing
3652
3653 #define BULLET " - "
3654
3655 static const char* state_names[] = {
3656 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3657 };
3658
3659 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3660 for (int i = 0; i < len; i++) {
3661 intptr_t e = start[i];
3662 st->print("%d : " INTPTR_FORMAT, i, e);
3663 if (MetaspaceObj::is_valid((Metadata*)e)) {
3664 st->print(" ");
3665 ((Metadata*)e)->print_value_on(st);
3666 }
3667 st->cr();
3668 }
3669 }
3670
3671 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3672 return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3673 }
3674
3675 const char* InstanceKlass::init_state_name() const {
3676 return state_names[init_state()];
3677 }
3678
3679 void InstanceKlass::print_on(outputStream* st) const {
3680 assert(is_klass(), "must be klass");
3681 Klass::print_on(st);
3682
3683 st->print(BULLET"instance size: %d", size_helper()); st->cr();
3684 st->print(BULLET"klass size: %d", size()); st->cr();
3685 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
3686 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
3687 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
3688 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
3689 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3690 st->print(BULLET"sub: ");
3691 Klass* sub = subklass();
3692 int n;
3693 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3694 if (n < MaxSubklassPrintSize) {
3695 sub->print_value_on(st);
3696 st->print(" ");
3697 }
3698 }
3699 if (n >= MaxSubklassPrintSize) st->print("(%zd more klasses...)", n - MaxSubklassPrintSize);
3700 st->cr();
3701
3702 if (is_interface()) {
3703 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
3704 if (nof_implementors() == 1) {
3705 st->print_cr(BULLET"implementor: ");
3706 st->print(" ");
3707 implementor()->print_value_on(st);
3708 st->cr();
3709 }
3710 }
3711
3712 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3713 st->print(BULLET"methods: "); methods()->print_value_on(st); st->cr();
3714 if (Verbose || WizardMode) {
3715 Array<Method*>* method_array = methods();
3716 for (int i = 0; i < method_array->length(); i++) {
3717 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3718 }
3719 }
3720 st->print(BULLET"method ordering: "); method_ordering()->print_value_on(st); st->cr();
3721 if (default_methods() != nullptr) {
3722 st->print(BULLET"default_methods: "); default_methods()->print_value_on(st); st->cr();
3723 if (Verbose) {
3724 Array<Method*>* method_array = default_methods();
3725 for (int i = 0; i < method_array->length(); i++) {
3726 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3727 }
3728 }
3729 }
3730 print_on_maybe_null(st, BULLET"default vtable indices: ", default_vtable_indices());
3731 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
3732 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3733
3734 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr();
3735
3736 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr();
3737 st->print(BULLET"secondary bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap); st->cr();
3738
3739 if (secondary_supers() != nullptr) {
3740 if (Verbose) {
3741 bool is_hashed = (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL);
3742 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length());
3743 for (int i = 0; i < _secondary_supers->length(); i++) {
3744 ResourceMark rm; // for external_name()
3745 Klass* secondary_super = _secondary_supers->at(i);
3746 st->print(BULLET"%2d:", i);
3747 if (is_hashed) {
3748 int home_slot = compute_home_slot(secondary_super, _secondary_supers_bitmap);
3768 print_on_maybe_null(st, BULLET"field type annotations: ", fields_type_annotations());
3769 {
3770 bool have_pv = false;
3771 // previous versions are linked together through the InstanceKlass
3772 for (InstanceKlass* pv_node = previous_versions();
3773 pv_node != nullptr;
3774 pv_node = pv_node->previous_versions()) {
3775 if (!have_pv)
3776 st->print(BULLET"previous version: ");
3777 have_pv = true;
3778 pv_node->constants()->print_value_on(st);
3779 }
3780 if (have_pv) st->cr();
3781 }
3782
3783 print_on_maybe_null(st, BULLET"generic signature: ", generic_signature());
3784 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
3785 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();
3786 print_on_maybe_null(st, BULLET"record components: ", record_components());
3787 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();
3788 if (java_mirror() != nullptr) {
3789 st->print(BULLET"java mirror: ");
3790 java_mirror()->print_value_on(st);
3791 st->cr();
3792 } else {
3793 st->print_cr(BULLET"java mirror: null");
3794 }
3795 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3796 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);
3797 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3798 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_itable(), itable_length(), st);
3799 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3800
3801 FieldPrinter print_static_field(st);
3802 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3803 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3804 FieldPrinter print_nonstatic_field(st);
3805 InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3806 ik->print_nonstatic_fields(&print_nonstatic_field);
3807
3808 st->print(BULLET"non-static oop maps (%d entries): ", nonstatic_oop_map_count());
3809 OopMapBlock* map = start_of_nonstatic_oop_maps();
3810 OopMapBlock* end_map = map + nonstatic_oop_map_count();
3811 while (map < end_map) {
3812 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3813 map++;
3814 }
3815 st->cr();
3816
3817 if (fieldinfo_search_table() != nullptr) {
3818 st->print_cr(BULLET"---- field info search table:");
3819 FieldInfoStream::print_search_table(st, _constants, _fieldinfo_stream, _fieldinfo_search_table);
3820 }
3821 }
3822
3823 void InstanceKlass::print_value_on(outputStream* st) const {
3824 assert(is_klass(), "must be klass");
3825 if (Verbose || WizardMode) access_flags().print_on(st);
3826 name()->print_value_on(st);
3827 }
3828
3829 void FieldPrinter::do_field(fieldDescriptor* fd) {
3830 _st->print(BULLET);
3831 if (_obj == nullptr) {
3832 fd->print_on(_st);
3833 _st->cr();
3834 } else {
3835 fd->print_on_for(_st, _obj);
3836 _st->cr();
3837 }
3838 }
3839
3840
3841 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3842 Klass::oop_print_on(obj, st);
3843
3844 if (this == vmClasses::String_klass()) {
3845 typeArrayOop value = java_lang_String::value(obj);
3846 juint length = java_lang_String::length(obj);
3847 if (value != nullptr &&
3848 value->is_typeArray() &&
3849 length <= (juint) value->length()) {
3850 st->print(BULLET"string: ");
3851 java_lang_String::print(obj, st);
3852 st->cr();
3853 }
3854 }
3855
3856 st->print_cr(BULLET"---- fields (total size %zu words):", oop_size(obj));
3857 FieldPrinter print_field(st, obj);
3858 print_nonstatic_fields(&print_field);
3859
3860 if (this == vmClasses::Class_klass()) {
3861 st->print(BULLET"signature: ");
3862 java_lang_Class::print_signature(obj, st);
3863 st->cr();
3864 Klass* real_klass = java_lang_Class::as_Klass(obj);
3865 if (real_klass != nullptr && real_klass->is_instance_klass()) {
3866 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj));
3867 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3868 }
3869 } else if (this == vmClasses::MethodType_klass()) {
3870 st->print(BULLET"signature: ");
3871 java_lang_invoke_MethodType::print_signature(obj, st);
3872 st->cr();
3873 }
3874 }
3875
3876 #ifndef PRODUCT
3877
|
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 _acmp_maps_offset(0),
597 _init_thread(nullptr),
598 _inline_layout_info_array(nullptr),
599 _loadable_descriptors(nullptr),
600 _adr_inlineklass_fixed_block(nullptr)
601 {
602 set_vtable_length(parser.vtable_size());
603 set_access_flags(parser.access_flags());
604 if (parser.is_hidden()) set_is_hidden();
605 set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
606 false));
607 if (parser.has_inline_fields()) {
608 set_has_inline_type_fields();
609 }
610
611 assert(nullptr == _methods, "underlying memory not zeroed?");
612 assert(is_instance_klass(), "is layout incorrect?");
613 assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
614 }
615
616 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
617 Array<Method*>* methods) {
618 if (methods != nullptr && methods != Universe::the_empty_method_array() &&
619 !methods->in_aot_cache()) {
620 for (int i = 0; i < methods->length(); i++) {
621 Method* method = methods->at(i);
622 if (method == nullptr) continue; // maybe null if error processing
623 // Only want to delete methods that are not executing for RedefineClasses.
624 // The previous version will point to them so they're not totally dangling
625 assert (!method->on_stack(), "shouldn't be called with methods on stack");
626 MetadataFactory::free_metadata(loader_data, method);
627 }
628 MetadataFactory::free_array<Method*>(loader_data, methods);
629 }
734
735 deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
736 set_transitive_interfaces(nullptr);
737 set_local_interfaces(nullptr);
738
739 if (fieldinfo_stream() != nullptr && !fieldinfo_stream()->in_aot_cache()) {
740 MetadataFactory::free_array<u1>(loader_data, fieldinfo_stream());
741 }
742 set_fieldinfo_stream(nullptr);
743
744 if (fieldinfo_search_table() != nullptr && !fieldinfo_search_table()->in_aot_cache()) {
745 MetadataFactory::free_array<u1>(loader_data, fieldinfo_search_table());
746 }
747 set_fieldinfo_search_table(nullptr);
748
749 if (fields_status() != nullptr && !fields_status()->in_aot_cache()) {
750 MetadataFactory::free_array<FieldStatus>(loader_data, fields_status());
751 }
752 set_fields_status(nullptr);
753
754 if (inline_layout_info_array() != nullptr) {
755 MetadataFactory::free_array<InlineLayoutInfo>(loader_data, inline_layout_info_array());
756 }
757 set_inline_layout_info_array(nullptr);
758
759 // If a method from a redefined class is using this constant pool, don't
760 // delete it, yet. The new class's previous version will point to this.
761 if (constants() != nullptr) {
762 assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
763 if (!constants()->in_aot_cache()) {
764 MetadataFactory::free_metadata(loader_data, constants());
765 }
766 // Delete any cached resolution errors for the constant pool
767 SystemDictionary::delete_resolution_error(constants());
768
769 set_constants(nullptr);
770 }
771
772 if (inner_classes() != nullptr &&
773 inner_classes() != Universe::the_empty_short_array() &&
774 !inner_classes()->in_aot_cache()) {
775 MetadataFactory::free_array<jushort>(loader_data, inner_classes());
776 }
777 set_inner_classes(nullptr);
778
779 if (nest_members() != nullptr &&
780 nest_members() != Universe::the_empty_short_array() &&
781 !nest_members()->in_aot_cache()) {
782 MetadataFactory::free_array<jushort>(loader_data, nest_members());
783 }
784 set_nest_members(nullptr);
785
786 if (permitted_subclasses() != nullptr &&
787 permitted_subclasses() != Universe::the_empty_short_array() &&
788 !permitted_subclasses()->in_aot_cache()) {
789 MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
790 }
791 set_permitted_subclasses(nullptr);
792
793 if (loadable_descriptors() != nullptr &&
794 loadable_descriptors() != Universe::the_empty_short_array() &&
795 !loadable_descriptors()->in_aot_cache()) {
796 MetadataFactory::free_array<jushort>(loader_data, loadable_descriptors());
797 }
798 set_loadable_descriptors(nullptr);
799
800 // We should deallocate the Annotations instance if it's not in shared spaces.
801 if (annotations() != nullptr && !annotations()->in_aot_cache()) {
802 MetadataFactory::free_metadata(loader_data, annotations());
803 }
804 set_annotations(nullptr);
805
806 SystemDictionaryShared::handle_class_unloading(this);
807
808 #if INCLUDE_CDS_JAVA_HEAP
809 if (CDSConfig::is_dumping_heap()) {
810 HeapShared::remove_scratch_objects(this);
811 }
812 #endif
813 }
814
815 bool InstanceKlass::is_record() const {
816 return _record_components != nullptr &&
817 is_final() &&
818 super() == vmClasses::Record_klass();
819 }
974 #ifdef ASSERT
975 {
976 Handle h_init_lock(THREAD, init_lock());
977 ObjectLocker ol(h_init_lock, THREAD);
978 assert(!is_initialized(), "sanity");
979 assert(!is_being_initialized(), "sanity");
980 assert(!is_in_error_state(), "sanity");
981 }
982 #endif
983
984 set_init_thread(THREAD);
985 set_initialization_state_and_notify(fully_initialized, CHECK);
986 }
987 #endif
988
989 bool InstanceKlass::verify_code(TRAPS) {
990 // 1) Verify the bytecodes
991 return Verifier::verify(this, should_verify_class(), THREAD);
992 }
993
994 static void load_classes_from_loadable_descriptors_attribute(InstanceKlass *ik, TRAPS) {
995 ResourceMark rm(THREAD);
996 if (ik->loadable_descriptors() != nullptr && PreloadClasses) {
997 HandleMark hm(THREAD);
998 for (int i = 0; i < ik->loadable_descriptors()->length(); i++) {
999 Symbol* sig = ik->constants()->symbol_at(ik->loadable_descriptors()->at(i));
1000 if (!Signature::has_envelope(sig)) continue;
1001 TempNewSymbol class_name = Signature::strip_envelope(sig);
1002 if (class_name == ik->name()) continue;
1003 log_info(class, preload)("Preloading of class %s during linking of class %s "
1004 "because of the class is listed in the LoadableDescriptors attribute",
1005 sig->as_C_string(), ik->name()->as_C_string());
1006 oop loader = ik->class_loader();
1007 Klass* klass = SystemDictionary::resolve_or_null(class_name,
1008 Handle(THREAD, loader), THREAD);
1009 if (HAS_PENDING_EXCEPTION) {
1010 CLEAR_PENDING_EXCEPTION;
1011 }
1012 if (klass != nullptr) {
1013 log_info(class, preload)("Preloading of class %s during linking of class %s "
1014 "(cause: LoadableDescriptors attribute) succeeded",
1015 class_name->as_C_string(), ik->name()->as_C_string());
1016 if (!klass->is_inline_klass()) {
1017 // Non value class are allowed by the current spec, but it could be an indication
1018 // of an issue so let's log a warning
1019 log_info(class, preload)("Preloading of class %s during linking of class %s "
1020 "(cause: LoadableDescriptors attribute) but loaded class is not a value class",
1021 class_name->as_C_string(), ik->name()->as_C_string());
1022 }
1023 } else {
1024 log_info(class, preload)("Preloading of class %s during linking of class %s "
1025 "(cause: LoadableDescriptors attribute) failed",
1026 class_name->as_C_string(), ik->name()->as_C_string());
1027 }
1028 }
1029 }
1030 }
1031
1032 void InstanceKlass::link_class(TRAPS) {
1033 assert(is_loaded(), "must be loaded");
1034 if (!is_linked()) {
1035 link_class_impl(CHECK);
1036 }
1037 }
1038
1039 // Called to verify that a class can link during initialization, without
1040 // throwing a VerifyError.
1041 bool InstanceKlass::link_class_or_fail(TRAPS) {
1042 assert(is_loaded(), "must be loaded");
1043 if (!is_linked()) {
1044 link_class_impl(CHECK_false);
1045 }
1046 return is_linked();
1047 }
1048
1049 bool InstanceKlass::link_class_impl(TRAPS) {
1050 if (CDSConfig::is_dumping_static_archive() && SystemDictionaryShared::has_class_failed_verification(this)) {
1051 // This is for CDS static dump only -- we use the in_error_state to indicate that
1082 THREAD_AND_LOCATION,
1083 vmSymbols::java_lang_IncompatibleClassChangeError(),
1084 "class %s has interface %s as super class",
1085 external_name(),
1086 super_klass->external_name()
1087 );
1088 return false;
1089 }
1090
1091 super_klass->link_class_impl(CHECK_false);
1092 }
1093
1094 // link all interfaces implemented by this class before linking this class
1095 Array<InstanceKlass*>* interfaces = local_interfaces();
1096 int num_interfaces = interfaces->length();
1097 for (int index = 0; index < num_interfaces; index++) {
1098 InstanceKlass* interk = interfaces->at(index);
1099 interk->link_class_impl(CHECK_false);
1100 }
1101
1102 if (EnableValhalla) {
1103 // Aggressively preloading all classes from the LoadableDescriptors attribute
1104 // so inline classes can be scalarized in the calling conventions computed below
1105 load_classes_from_loadable_descriptors_attribute(this, THREAD);
1106 assert(!HAS_PENDING_EXCEPTION, "Shouldn't have pending exceptions from call above");
1107 }
1108
1109 // in case the class is linked in the process of linking its superclasses
1110 if (is_linked()) {
1111 return true;
1112 }
1113
1114 // trace only the link time for this klass that includes
1115 // the verification time
1116 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
1117 ClassLoader::perf_class_link_selftime(),
1118 ClassLoader::perf_classes_linked(),
1119 jt->get_thread_stat()->perf_recursion_counts_addr(),
1120 jt->get_thread_stat()->perf_timers_addr(),
1121 PerfClassTraceTime::CLASS_LINK);
1122
1123 // verification & rewriting
1124 {
1125 HandleMark hm(THREAD);
1126 Handle h_init_lock(THREAD, init_lock());
1127 ObjectLocker ol(h_init_lock, CHECK_PREEMPTABLE_false);
1128 // Don't allow preemption if we link/initialize classes below,
1412 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1413 ss.as_string(), cause);
1414 }
1415 } else {
1416
1417 // Step 6
1418 set_init_state(being_initialized);
1419 set_init_thread(jt);
1420 if (debug_logging_enabled) {
1421 ResourceMark rm(jt);
1422 log_debug(class, init)("Thread \"%s\" is initializing %s",
1423 jt->name(), external_name());
1424 }
1425 }
1426 }
1427
1428 // Block preemption once we are the initializer thread. Unmounting now
1429 // would complicate the reentrant case (identity is platform thread).
1430 NoPreemptMark npm(THREAD);
1431
1432 // Pre-allocating an all-zero value to be used to reset nullable flat storages
1433 if (is_inline_klass()) {
1434 InlineKlass* vk = InlineKlass::cast(this);
1435 if (vk->has_nullable_atomic_layout()) {
1436 oop val = vk->allocate_instance(THREAD);
1437 if (HAS_PENDING_EXCEPTION) {
1438 Handle e(THREAD, PENDING_EXCEPTION);
1439 CLEAR_PENDING_EXCEPTION;
1440 {
1441 EXCEPTION_MARK;
1442 add_initialization_error(THREAD, e);
1443 // Locks object, set state, and notify all waiting threads
1444 set_initialization_state_and_notify(initialization_error, THREAD);
1445 CLEAR_PENDING_EXCEPTION;
1446 }
1447 THROW_OOP(e());
1448 }
1449 vk->set_null_reset_value(val);
1450 }
1451 }
1452
1453 // Step 7
1454 // Next, if C is a class rather than an interface, initialize it's super class and super
1455 // interfaces.
1456 if (!is_interface()) {
1457 Klass* super_klass = super();
1458 if (super_klass != nullptr && super_klass->should_be_initialized()) {
1459 super_klass->initialize(THREAD);
1460 }
1461 // If C implements any interface that declares a non-static, concrete method,
1462 // the initialization of C triggers initialization of its super interfaces.
1463 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1464 // having a superinterface that declares, non-static, concrete methods
1465 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1466 initialize_super_interfaces(THREAD);
1467 }
1468
1469 // If any exceptions, complete abruptly, throwing the same exception as above.
1470 if (HAS_PENDING_EXCEPTION) {
1471 Handle e(THREAD, PENDING_EXCEPTION);
1472 CLEAR_PENDING_EXCEPTION;
1473 {
1474 EXCEPTION_MARK;
1475 add_initialization_error(THREAD, e);
1476 // Locks object, set state, and notify all waiting threads
1477 set_initialization_state_and_notify(initialization_error, THREAD);
1478 CLEAR_PENDING_EXCEPTION;
1479 }
1480 DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1481 THROW_OOP(e());
1482 }
1483 }
1484
1485 // Step 8
1486 {
1487 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1488 if (class_initializer() != nullptr) {
1489 // Timer includes any side effects of class initialization (resolution,
1490 // etc), but not recursive entry into call_class_initializer().
1491 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1492 ClassLoader::perf_class_init_selftime(),
1493 ClassLoader::perf_classes_inited(),
1494 jt->get_thread_stat()->perf_recursion_counts_addr(),
1495 jt->get_thread_stat()->perf_timers_addr(),
1496 PerfClassTraceTime::CLASS_CLINIT);
1497 call_class_initializer(THREAD);
1498 } else {
1499 // The elapsed time is so small it's not worth counting.
1500 if (UsePerfData) {
1501 ClassLoader::perf_classes_inited()->inc();
1502 }
1503 call_class_initializer(THREAD);
1504 }
1505
1506 if (has_strict_static_fields() && !HAS_PENDING_EXCEPTION) {
1507 // Step 9 also verifies that strict static fields have been initialized.
1508 // Status bits were set in ClassFileParser::post_process_parsed_stream.
1509 // After <clinit>, bits must all be clear, or else we must throw an error.
1510 // This is an extremely fast check, so we won't bother with a timer.
1511 assert(fields_status() != nullptr, "");
1512 Symbol* bad_strict_static = nullptr;
1513 for (int index = 0; index < fields_status()->length(); index++) {
1514 // Very fast loop over single byte array looking for a set bit.
1515 if (fields_status()->adr_at(index)->is_strict_static_unset()) {
1516 // This strict static field has not been set by the class initializer.
1517 // Note that in the common no-error case, we read no field metadata.
1518 // We only unpack it when we need to report an error.
1519 FieldInfo fi = field(index);
1520 bad_strict_static = fi.name(constants());
1521 if (debug_logging_enabled) {
1522 ResourceMark rm(jt);
1523 const char* msg = format_strict_static_message(bad_strict_static);
1524 log_debug(class, init)("%s", msg);
1525 } else {
1526 // If we are not logging, do not bother to look for a second offense.
1527 break;
1528 }
1529 }
1530 }
1531 if (bad_strict_static != nullptr) {
1532 throw_strict_static_exception(bad_strict_static, "is unset after initialization of", THREAD);
1533 }
1534 }
1535 }
1536
1537 // Step 9
1538 if (!HAS_PENDING_EXCEPTION) {
1539 set_initialization_state_and_notify(fully_initialized, CHECK);
1540 DEBUG_ONLY(vtable().verify(tty, true);)
1541 CompilationPolicy::replay_training_at_init(this, THREAD);
1542 }
1543 else {
1544 // Step 10 and 11
1545 Handle e(THREAD, PENDING_EXCEPTION);
1546 CLEAR_PENDING_EXCEPTION;
1547 // JVMTI has already reported the pending exception
1548 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1549 JvmtiExport::clear_detected_exception(jt);
1550 {
1551 EXCEPTION_MARK;
1552 add_initialization_error(THREAD, e);
1553 set_initialization_state_and_notify(initialization_error, THREAD);
1554 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1568 }
1569 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1570 }
1571
1572
1573 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1574 Handle h_init_lock(THREAD, init_lock());
1575 if (h_init_lock() != nullptr) {
1576 ObjectLocker ol(h_init_lock, THREAD);
1577 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1578 set_init_state(state);
1579 fence_and_clear_init_lock();
1580 ol.notify_all(CHECK);
1581 } else {
1582 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1583 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1584 set_init_state(state);
1585 }
1586 }
1587
1588 void InstanceKlass::notify_strict_static_access(int field_index, bool is_writing, TRAPS) {
1589 guarantee(field_index >= 0 && field_index < fields_status()->length(), "valid field index");
1590 DEBUG_ONLY(FieldInfo debugfi = field(field_index));
1591 assert(debugfi.access_flags().is_strict(), "");
1592 assert(debugfi.access_flags().is_static(), "");
1593 FieldStatus& fs = *fields_status()->adr_at(field_index);
1594 LogTarget(Trace, class, init) lt;
1595 if (lt.is_enabled()) {
1596 ResourceMark rm(THREAD);
1597 LogStream ls(lt);
1598 FieldInfo fi = field(field_index);
1599 ls.print("notify %s %s %s%s ",
1600 external_name(), is_writing? "Write" : "Read",
1601 fs.is_strict_static_unset() ? "Unset" : "(set)",
1602 fs.is_strict_static_unread() ? "+Unread" : "");
1603 fi.print(&ls, constants());
1604 }
1605 if (fs.is_strict_static_unset()) {
1606 assert(fs.is_strict_static_unread(), "ClassFileParser resp.");
1607 // If it is not set, there are only two reasonable things we can do here:
1608 // - mark it set if this is putstatic
1609 // - throw an error (Read-Before-Write) if this is getstatic
1610
1611 // The unset state is (or should be) transient, and observable only in one
1612 // thread during the execution of <clinit>. Something is wrong here as this
1613 // should not be possible
1614 guarantee(is_reentrant_initialization(THREAD), "unscoped access to strict static");
1615 if (is_writing) {
1616 // clear the "unset" bit, since the field is actually going to be written
1617 fs.update_strict_static_unset(false);
1618 } else {
1619 // throw an IllegalStateException, since we are reading before writing
1620 // see also InstanceKlass::initialize_impl, Step 8 (at end)
1621 Symbol* bad_strict_static = field(field_index).name(constants());
1622 throw_strict_static_exception(bad_strict_static, "is unset before first read in", CHECK);
1623 }
1624 } else {
1625 // Ensure no write after read for final strict statics
1626 FieldInfo fi = field(field_index);
1627 bool is_final = fi.access_flags().is_final();
1628 if (is_final) {
1629 // no final write after read, so observing a constant freezes it, as if <clinit> ended early
1630 // (maybe we could trust the constant a little earlier, before <clinit> ends)
1631 if (is_writing && !fs.is_strict_static_unread()) {
1632 Symbol* bad_strict_static = fi.name(constants());
1633 throw_strict_static_exception(bad_strict_static, "is set after read (as final) in", CHECK);
1634 } else if (!is_writing && fs.is_strict_static_unread()) {
1635 fs.update_strict_static_unread(false);
1636 }
1637 }
1638 }
1639 }
1640
1641 void InstanceKlass::throw_strict_static_exception(Symbol* field_name, const char* when, TRAPS) {
1642 ResourceMark rm(THREAD);
1643 const char* msg = format_strict_static_message(field_name, when);
1644 THROW_MSG(vmSymbols::java_lang_IllegalStateException(), msg);
1645 }
1646
1647 const char* InstanceKlass::format_strict_static_message(Symbol* field_name, const char* when) {
1648 stringStream ss;
1649 ss.print("Strict static \"%s\" %s %s",
1650 field_name->as_C_string(),
1651 when == nullptr ? "is unset in" : when,
1652 external_name());
1653 return ss.as_string();
1654 }
1655
1656 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1657 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1658 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1659 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1660
1661 DeoptimizationScope deopt_scope;
1662 {
1663 MutexLocker ml(current, Compile_lock);
1664
1665 set_init_state(InstanceKlass::loaded);
1666 // make sure init_state store is already done.
1667 // The compiler reads the hierarchy outside of the Compile_lock.
1668 // Access ordering is used to add to hierarchy.
1669
1670 // Link into hierarchy.
1671 append_to_sibling_list(); // add to superklass/sibling list
1672 process_interfaces(); // handle all "implements" declarations
1673
1674 // Now mark all code that depended on old class hierarchy.
1675 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1886 : vmSymbols::java_lang_IllegalAccessException(), external_name());
1887 }
1888 }
1889
1890 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
1891 // Need load-acquire for lock-free read
1892 if (array_klasses_acquire() == nullptr) {
1893
1894 // Recursively lock array allocation
1895 RecursiveLocker rl(MultiArray_lock, THREAD);
1896
1897 // Check if another thread created the array klass while we were waiting for the lock.
1898 if (array_klasses() == nullptr) {
1899 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
1900 // use 'release' to pair with lock-free load
1901 release_set_array_klasses(k);
1902 }
1903 }
1904
1905 // array_klasses() will always be set at this point
1906 ArrayKlass* ak = array_klasses();
1907 assert(ak != nullptr, "should be set");
1908 return ak->array_klass(n, THREAD);
1909 }
1910
1911 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1912 // Need load-acquire for lock-free read
1913 ArrayKlass* ak = array_klasses_acquire();
1914 if (ak == nullptr) {
1915 return nullptr;
1916 } else {
1917 return ak->array_klass_or_null(n);
1918 }
1919 }
1920
1921 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1922 return array_klass(1, THREAD);
1923 }
1924
1925 ArrayKlass* InstanceKlass::array_klass_or_null() {
1926 return array_klass_or_null(1);
1927 }
1928
1929 static int call_class_initializer_counter = 0; // for debugging
1930
1931 Method* InstanceKlass::class_initializer() const {
1932 Method* clinit = find_method(
1933 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1934 if (clinit != nullptr && clinit->is_class_initializer()) {
1935 return clinit;
1936 }
1937 return nullptr;
1938 }
1939
1940 void InstanceKlass::call_class_initializer(TRAPS) {
1941 if (ReplayCompiles &&
1942 (ReplaySuppressInitializers == 1 ||
1943 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1944 // Hide the existence of the initializer for the purpose of replaying the compile
1945 return;
1946 }
1947
1948 #if INCLUDE_CDS
1949 // This is needed to ensure the consistency of the archived heap objects.
1950 if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
1951 AOTClassInitializer::call_runtime_setup(THREAD, this);
1952 return;
1953 } else if (has_archived_enum_objs()) {
1954 assert(in_aot_cache(), "must be");
2023
2024 void InstanceKlass::mask_for(const methodHandle& method, int bci,
2025 InterpreterOopMap* entry_for) {
2026 // Lazily create the _oop_map_cache at first request.
2027 // Load_acquire is needed to safely get instance published with CAS by another thread.
2028 OopMapCache* oop_map_cache = AtomicAccess::load_acquire(&_oop_map_cache);
2029 if (oop_map_cache == nullptr) {
2030 // Try to install new instance atomically.
2031 oop_map_cache = new OopMapCache();
2032 OopMapCache* other = AtomicAccess::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
2033 if (other != nullptr) {
2034 // Someone else managed to install before us, ditch local copy and use the existing one.
2035 delete oop_map_cache;
2036 oop_map_cache = other;
2037 }
2038 }
2039 // _oop_map_cache is constant after init; lookup below does its own locking.
2040 oop_map_cache->lookup(method, bci, entry_for);
2041 }
2042
2043
2044 FieldInfo InstanceKlass::field(int index) const {
2045 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2046 if (fs.index() == index) {
2047 return fs.to_FieldInfo();
2048 }
2049 }
2050 fatal("Field not found");
2051 return FieldInfo();
2052 }
2053
2054 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
2055 JavaFieldStream fs(this);
2056 if (fs.lookup(name, sig)) {
2057 assert(fs.name() == name, "name must match");
2058 assert(fs.signature() == sig, "signature must match");
2059 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2060 return true;
2061 }
2062 return false;
2103
2104 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
2105 // search order according to newest JVM spec (5.4.3.2, p.167).
2106 // 1) search for field in current klass
2107 if (find_local_field(name, sig, fd)) {
2108 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
2109 }
2110 // 2) search for field recursively in direct superinterfaces
2111 if (is_static) {
2112 Klass* intf = find_interface_field(name, sig, fd);
2113 if (intf != nullptr) return intf;
2114 }
2115 // 3) apply field lookup recursively if superclass exists
2116 { InstanceKlass* supr = super();
2117 if (supr != nullptr) return supr->find_field(name, sig, is_static, fd);
2118 }
2119 // 4) otherwise field lookup fails
2120 return nullptr;
2121 }
2122
2123 bool InstanceKlass::contains_field_offset(int offset) {
2124 if (this->is_inline_klass()) {
2125 InlineKlass* vk = InlineKlass::cast(this);
2126 return offset >= vk->payload_offset() && offset < (vk->payload_offset() + vk->payload_size_in_bytes());
2127 } else {
2128 fieldDescriptor fd;
2129 return find_field_from_offset(offset, false, &fd);
2130 }
2131 }
2132
2133 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2134 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2135 if (fs.offset() == offset) {
2136 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2137 if (fd->is_static() == is_static) return true;
2138 }
2139 }
2140 return false;
2141 }
2142
2143
2144 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2145 const InstanceKlass* klass = this;
2146 while (klass != nullptr) {
2147 if (klass->find_local_field_from_offset(offset, is_static, fd)) {
2148 return true;
2149 }
2150 klass = klass->super();
2151 }
2495 }
2496
2497 // uncached_lookup_method searches both the local class methods array and all
2498 // superclasses methods arrays, skipping any overpass methods in superclasses,
2499 // and possibly skipping private methods.
2500 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2501 const Symbol* signature,
2502 OverpassLookupMode overpass_mode,
2503 PrivateLookupMode private_mode) const {
2504 OverpassLookupMode overpass_local_mode = overpass_mode;
2505 const InstanceKlass* klass = this;
2506 while (klass != nullptr) {
2507 Method* const method = klass->find_method_impl(name,
2508 signature,
2509 overpass_local_mode,
2510 StaticLookupMode::find,
2511 private_mode);
2512 if (method != nullptr) {
2513 return method;
2514 }
2515 if (name == vmSymbols::object_initializer_name()) {
2516 break; // <init> is never inherited
2517 }
2518 klass = klass->super();
2519 overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses
2520 }
2521 return nullptr;
2522 }
2523
2524 #ifdef ASSERT
2525 // search through class hierarchy and return true if this class or
2526 // one of the superclasses was redefined
2527 bool InstanceKlass::has_redefined_this_or_super() const {
2528 const InstanceKlass* klass = this;
2529 while (klass != nullptr) {
2530 if (klass->has_been_redefined()) {
2531 return true;
2532 }
2533 klass = klass->super();
2534 }
2535 return false;
2536 }
2537 #endif
2910 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2911
2912 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2913 / itableOffsetEntry::size();
2914
2915 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2916 if (ioe->interface_klass() != nullptr) {
2917 it->push(ioe->interface_klass_addr());
2918 itableMethodEntry* ime = ioe->first_method_entry(this);
2919 int n = klassItable::method_count_for_interface(ioe->interface_klass());
2920 for (int index = 0; index < n; index ++) {
2921 it->push(ime[index].method_addr());
2922 }
2923 }
2924 }
2925 }
2926
2927 it->push(&_nest_host);
2928 it->push(&_nest_members);
2929 it->push(&_permitted_subclasses);
2930 it->push(&_loadable_descriptors);
2931 it->push(&_record_components);
2932 it->push(&_inline_layout_info_array, MetaspaceClosure::_writable);
2933 }
2934
2935 #if INCLUDE_CDS
2936 void InstanceKlass::remove_unshareable_info() {
2937
2938 if (is_linked()) {
2939 assert(can_be_verified_at_dumptime(), "must be");
2940 // Remember this so we can avoid walking the hierarchy at runtime.
2941 set_verified_at_dump_time();
2942 }
2943
2944 _misc_flags.set_has_init_deps_processed(false);
2945
2946 Klass::remove_unshareable_info();
2947
2948 if (SystemDictionaryShared::has_class_failed_verification(this)) {
2949 // Classes are attempted to link during dumping and may fail,
2950 // but these classes are still in the dictionary and class list in CLD.
2951 // If the class has failed verification, there is nothing else to remove.
2952 return;
2960
2961 { // Otherwise this needs to take out the Compile_lock.
2962 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2963 init_implementor();
2964 }
2965
2966 // Call remove_unshareable_info() on other objects that belong to this class, except
2967 // for constants()->remove_unshareable_info(), which is called in a separate pass in
2968 // ArchiveBuilder::make_klasses_shareable(),
2969
2970 for (int i = 0; i < methods()->length(); i++) {
2971 Method* m = methods()->at(i);
2972 m->remove_unshareable_info();
2973 }
2974
2975 // do array classes also.
2976 if (array_klasses() != nullptr) {
2977 array_klasses()->remove_unshareable_info();
2978 }
2979
2980 // These are not allocated from metaspace. They are safe to set to nullptr.
2981 _source_debug_extension = nullptr;
2982 _dep_context = nullptr;
2983 _osr_nmethods_head = nullptr;
2984 #if INCLUDE_JVMTI
2985 _breakpoints = nullptr;
2986 _previous_versions = nullptr;
2987 _cached_class_file = nullptr;
2988 _jvmti_cached_class_field_map = nullptr;
2989 #endif
2990
2991 _init_thread = nullptr;
2992 _methods_jmethod_ids = nullptr;
2993 _jni_ids = nullptr;
2994 _oop_map_cache = nullptr;
2995 if (CDSConfig::is_dumping_method_handles() && HeapShared::is_lambda_proxy_klass(this)) {
2996 // keep _nest_host
2997 } else {
2998 // clear _nest_host to ensure re-load at runtime
2999 _nest_host = nullptr;
3000 }
3051 void InstanceKlass::compute_has_loops_flag_for_methods() {
3052 Array<Method*>* methods = this->methods();
3053 for (int index = 0; index < methods->length(); ++index) {
3054 Method* m = methods->at(index);
3055 if (!m->is_overpass()) { // work around JDK-8305771
3056 m->compute_has_loops_flag();
3057 }
3058 }
3059 }
3060
3061 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
3062 PackageEntry* pkg_entry, TRAPS) {
3063 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
3064 // before the InstanceKlass is added to the SystemDictionary. Make
3065 // sure the current state is <loaded.
3066 assert(!is_loaded(), "invalid init state");
3067 assert(!shared_loading_failed(), "Must not try to load failed class again");
3068 set_package(loader_data, pkg_entry, CHECK);
3069 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
3070
3071 if (is_inline_klass()) {
3072 InlineKlass::cast(this)->initialize_calling_convention(CHECK);
3073 }
3074
3075 Array<Method*>* methods = this->methods();
3076 int num_methods = methods->length();
3077 for (int index = 0; index < num_methods; ++index) {
3078 methods->at(index)->restore_unshareable_info(CHECK);
3079 }
3080 #if INCLUDE_JVMTI
3081 if (JvmtiExport::has_redefined_a_class()) {
3082 // Reinitialize vtable because RedefineClasses may have changed some
3083 // entries in this vtable for super classes so the CDS vtable might
3084 // point to old or obsolete entries. RedefineClasses doesn't fix up
3085 // vtables in the shared system dictionary, only the main one.
3086 // It also redefines the itable too so fix that too.
3087 // First fix any default methods that point to a super class that may
3088 // have been redefined.
3089 bool trace_name_printed = false;
3090 adjust_default_methods(&trace_name_printed);
3091 if (verified_at_dump_time()) {
3092 // Initialize vtable and itable for classes which can be verified at dump time.
3093 // Unlinked classes such as old classes with major version < 50 cannot be verified
3094 // at dump time.
3095 vtable().initialize_vtable();
3096 itable().initialize_itable();
3097 }
3098 }
3099 #endif // INCLUDE_JVMTI
3100
3101 // restore constant pool resolved references
3102 constants()->restore_unshareable_info(CHECK);
3103
3104 if (array_klasses() != nullptr) {
3105 // To get a consistent list of classes we need MultiArray_lock to ensure
3106 // array classes aren't observed while they are being restored.
3107 RecursiveLocker rl(MultiArray_lock, THREAD);
3108 assert(this == ObjArrayKlass::cast(array_klasses())->bottom_klass(), "sanity");
3109 // Array classes have null protection domain.
3110 // --> see ArrayKlass::complete_create_array_klass()
3111 if (class_loader_data() == nullptr) {
3112 ResourceMark rm(THREAD);
3113 log_debug(cds)(" loader_data %s ", loader_data == nullptr ? "nullptr" : "non null");
3114 log_debug(cds)(" this %s array_klasses %s ", this->name()->as_C_string(), array_klasses()->name()->as_C_string());
3115 }
3116 assert(!array_klasses()->is_refined_objArray_klass(), "must be non-refined objarrayklass");
3117 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
3118 }
3119
3120 // Initialize @ValueBased class annotation if not already set in the archived klass.
3121 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
3122 set_is_value_based();
3123 }
3124
3125 DEBUG_ONLY(FieldInfoStream::validate_search_table(_constants, _fieldinfo_stream, _fieldinfo_search_table));
3126 }
3127
3128 bool InstanceKlass::can_be_verified_at_dumptime() const {
3129 if (AOTMetaspace::in_aot_cache(this)) {
3130 // This is a class that was dumped into the base archive, so we know
3131 // it was verified at dump time.
3132 return true;
3133 }
3134
3135 if (CDSConfig::is_preserving_verification_constraints()) {
3136 return true;
3252 constants()->release_C_heap_structures();
3253 }
3254 }
3255
3256 // The constant pool is on stack if any of the methods are executing or
3257 // referenced by handles.
3258 bool InstanceKlass::on_stack() const {
3259 return _constants->on_stack();
3260 }
3261
3262 Symbol* InstanceKlass::source_file_name() const { return _constants->source_file_name(); }
3263 u2 InstanceKlass::source_file_name_index() const { return _constants->source_file_name_index(); }
3264 void InstanceKlass::set_source_file_name_index(u2 sourcefile_index) { _constants->set_source_file_name_index(sourcefile_index); }
3265
3266 // minor and major version numbers of class file
3267 u2 InstanceKlass::minor_version() const { return _constants->minor_version(); }
3268 void InstanceKlass::set_minor_version(u2 minor_version) { _constants->set_minor_version(minor_version); }
3269 u2 InstanceKlass::major_version() const { return _constants->major_version(); }
3270 void InstanceKlass::set_major_version(u2 major_version) { _constants->set_major_version(major_version); }
3271
3272 bool InstanceKlass::supports_inline_types() const {
3273 return major_version() >= Verifier::VALUE_TYPES_MAJOR_VERSION && minor_version() == Verifier::JAVA_PREVIEW_MINOR_VERSION;
3274 }
3275
3276 const InstanceKlass* InstanceKlass::get_klass_version(int version) const {
3277 for (const InstanceKlass* ik = this; ik != nullptr; ik = ik->previous_versions()) {
3278 if (ik->constants()->version() == version) {
3279 return ik;
3280 }
3281 }
3282 return nullptr;
3283 }
3284
3285 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
3286 if (array == nullptr) {
3287 _source_debug_extension = nullptr;
3288 } else {
3289 // Adding one to the attribute length in order to store a null terminator
3290 // character could cause an overflow because the attribute length is
3291 // already coded with an u4 in the classfile, but in practice, it's
3292 // unlikely to happen.
3293 assert((length+1) > length, "Overflow checking");
3294 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
3295 for (int i = 0; i < length; i++) {
3296 sde[i] = array[i];
3297 }
3298 sde[length] = '\0';
3299 _source_debug_extension = sde;
3300 }
3301 }
3302
3303 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); }
3304 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); }
3305 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); }
3306
3307 const char* InstanceKlass::signature_name() const {
3308 return signature_name_of_carrier(JVM_SIGNATURE_CLASS);
3309 }
3310
3311 const char* InstanceKlass::signature_name_of_carrier(char c) const {
3312 // Get the internal name as a c string
3313 const char* src = (const char*) (name()->as_C_string());
3314 const int src_length = (int)strlen(src);
3315
3316 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
3317
3318 // Add L or Q as type indicator
3319 int dest_index = 0;
3320 dest[dest_index++] = c;
3321
3322 // Add the actual class name
3323 for (int src_index = 0; src_index < src_length; ) {
3324 dest[dest_index++] = src[src_index++];
3325 }
3326
3327 if (is_hidden()) { // Replace the last '+' with a '.'.
3328 for (int index = (int)src_length; index > 0; index--) {
3329 if (dest[index] == '+') {
3330 dest[index] = JVM_SIGNATURE_DOT;
3331 break;
3332 }
3333 }
3334 }
3335
3336 // Add the semicolon and the null
3337 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3338 dest[dest_index] = '\0';
3339 return dest;
3340 }
3581 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3582 constantPoolHandle i_cp(THREAD, constants());
3583 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3584 int ioff = iter.inner_class_info_index();
3585 if (ioff != 0) {
3586 // Check to see if the name matches the class we're looking for
3587 // before attempting to find the class.
3588 if (i_cp->klass_name_at_matches(this, ioff)) {
3589 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3590 if (this == inner_klass) {
3591 *ooff = iter.outer_class_info_index();
3592 *noff = iter.inner_name_index();
3593 return true;
3594 }
3595 }
3596 }
3597 }
3598 return false;
3599 }
3600
3601 void InstanceKlass::check_can_be_annotated_with_NullRestricted(InstanceKlass* type, Symbol* container_klass_name, TRAPS) {
3602 assert(type->is_instance_klass(), "Sanity check");
3603 if (type->is_identity_class()) {
3604 ResourceMark rm(THREAD);
3605 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
3606 err_msg("Class %s expects class %s to be a value class, but it is an identity class",
3607 container_klass_name->as_C_string(),
3608 type->external_name()));
3609 }
3610
3611 if (type->is_abstract()) {
3612 ResourceMark rm(THREAD);
3613 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
3614 err_msg("Class %s expects class %s to be concrete value type, but it is an abstract class",
3615 container_klass_name->as_C_string(),
3616 type->external_name()));
3617 }
3618 }
3619
3620 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3621 InstanceKlass* outer_klass = nullptr;
3622 *inner_is_member = false;
3623 int ooff = 0, noff = 0;
3624 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3625 if (has_inner_classes_attr) {
3626 constantPoolHandle i_cp(THREAD, constants());
3627 if (ooff != 0) {
3628 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3629 if (!ok->is_instance_klass()) {
3630 // If the outer class is not an instance klass then it cannot have
3631 // declared any inner classes.
3632 ResourceMark rm(THREAD);
3633 // Names are all known to be < 64k so we know this formatted message is not excessively large.
3634 Exceptions::fthrow(
3635 THREAD_AND_LOCATION,
3636 vmSymbols::java_lang_IncompatibleClassChangeError(),
3637 "%s and %s disagree on InnerClasses attribute",
3638 ok->external_name(),
3639 external_name());
3666 u2 InstanceKlass::compute_modifier_flags() const {
3667 u2 access = access_flags().as_unsigned_short();
3668
3669 // But check if it happens to be member class.
3670 InnerClassesIterator iter(this);
3671 for (; !iter.done(); iter.next()) {
3672 int ioff = iter.inner_class_info_index();
3673 // Inner class attribute can be zero, skip it.
3674 // Strange but true: JVM spec. allows null inner class refs.
3675 if (ioff == 0) continue;
3676
3677 // only look at classes that are already loaded
3678 // since we are looking for the flags for our self.
3679 Symbol* inner_name = constants()->klass_name_at(ioff);
3680 if (name() == inner_name) {
3681 // This is really a member class.
3682 access = iter.inner_access_flags();
3683 break;
3684 }
3685 }
3686 return access;
3687 }
3688
3689 jint InstanceKlass::jvmti_class_status() const {
3690 jint result = 0;
3691
3692 if (is_linked()) {
3693 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3694 }
3695
3696 if (is_initialized()) {
3697 assert(is_linked(), "Class status is not consistent");
3698 result |= JVMTI_CLASS_STATUS_INITIALIZED;
3699 }
3700 if (is_in_error_state()) {
3701 result |= JVMTI_CLASS_STATUS_ERROR;
3702 }
3703 return result;
3704 }
3705
3706 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
3920 }
3921 osr = osr->osr_link();
3922 }
3923
3924 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
3925 if (best != nullptr && best->comp_level() >= comp_level) {
3926 return best;
3927 }
3928 return nullptr;
3929 }
3930
3931 // -----------------------------------------------------------------------------------------------------
3932 // Printing
3933
3934 #define BULLET " - "
3935
3936 static const char* state_names[] = {
3937 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3938 };
3939
3940 static void print_vtable(address self, intptr_t* start, int len, outputStream* st) {
3941 ResourceMark rm;
3942 int* forward_refs = NEW_RESOURCE_ARRAY(int, len);
3943 for (int i = 0; i < len; i++) forward_refs[i] = 0;
3944 for (int i = 0; i < len; i++) {
3945 intptr_t e = start[i];
3946 st->print("%d : " INTPTR_FORMAT, i, e);
3947 if (forward_refs[i] != 0) {
3948 int from = forward_refs[i];
3949 int off = (int) start[from];
3950 st->print(" (offset %d <= [%d])", off, from);
3951 }
3952 if (MetaspaceObj::is_valid((Metadata*)e)) {
3953 st->print(" ");
3954 ((Metadata*)e)->print_value_on(st);
3955 } else if (self != nullptr && e > 0 && e < 0x10000) {
3956 address location = self + e;
3957 int index = (int)((intptr_t*)location - start);
3958 st->print(" (offset %d => [%d])", (int)e, index);
3959 if (index >= 0 && index < len)
3960 forward_refs[index] = i;
3961 }
3962 st->cr();
3963 }
3964 }
3965
3966 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3967 return print_vtable(nullptr, reinterpret_cast<intptr_t*>(start), len, st);
3968 }
3969
3970 template<typename T>
3971 static void print_array_on(outputStream* st, Array<T>* array) {
3972 if (array == nullptr) { st->print_cr("nullptr"); return; }
3973 array->print_value_on(st); st->cr();
3974 if (Verbose || WizardMode) {
3975 for (int i = 0; i < array->length(); i++) {
3976 st->print("%d : ", i); array->at(i)->print_value_on(st); st->cr();
3977 }
3978 }
3979 }
3980
3981 static void print_array_on(outputStream* st, Array<int>* array) {
3982 if (array == nullptr) { st->print_cr("nullptr"); return; }
3983 array->print_value_on(st); st->cr();
3984 if (Verbose || WizardMode) {
3985 for (int i = 0; i < array->length(); i++) {
3986 st->print("%d : %d", i, array->at(i)); st->cr();
3987 }
3988 }
3989 }
3990
3991 const char* InstanceKlass::init_state_name() const {
3992 return state_names[init_state()];
3993 }
3994
3995 void InstanceKlass::print_on(outputStream* st) const {
3996 assert(is_klass(), "must be klass");
3997 Klass::print_on(st);
3998
3999 st->print(BULLET"instance size: %d", size_helper()); st->cr();
4000 st->print(BULLET"klass size: %d", size()); st->cr();
4001 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
4002 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
4003 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
4004 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
4005 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
4006 st->print(BULLET"sub: ");
4007 Klass* sub = subklass();
4008 int n;
4009 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
4010 if (n < MaxSubklassPrintSize) {
4011 sub->print_value_on(st);
4012 st->print(" ");
4013 }
4014 }
4015 if (n >= MaxSubklassPrintSize) st->print("(%zd more klasses...)", n - MaxSubklassPrintSize);
4016 st->cr();
4017
4018 if (is_interface()) {
4019 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
4020 if (nof_implementors() == 1) {
4021 st->print_cr(BULLET"implementor: ");
4022 st->print(" ");
4023 implementor()->print_value_on(st);
4024 st->cr();
4025 }
4026 }
4027
4028 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
4029 st->print(BULLET"methods: "); print_array_on(st, methods());
4030 st->print(BULLET"method ordering: "); print_array_on(st, method_ordering());
4031 if (default_methods() != nullptr) {
4032 st->print(BULLET"default_methods: "); print_array_on(st, default_methods());
4033 }
4034 print_on_maybe_null(st, BULLET"default vtable indices: ", default_vtable_indices());
4035 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
4036 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
4037
4038 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr();
4039
4040 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr();
4041 st->print(BULLET"secondary bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap); st->cr();
4042
4043 if (secondary_supers() != nullptr) {
4044 if (Verbose) {
4045 bool is_hashed = (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL);
4046 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length());
4047 for (int i = 0; i < _secondary_supers->length(); i++) {
4048 ResourceMark rm; // for external_name()
4049 Klass* secondary_super = _secondary_supers->at(i);
4050 st->print(BULLET"%2d:", i);
4051 if (is_hashed) {
4052 int home_slot = compute_home_slot(secondary_super, _secondary_supers_bitmap);
4072 print_on_maybe_null(st, BULLET"field type annotations: ", fields_type_annotations());
4073 {
4074 bool have_pv = false;
4075 // previous versions are linked together through the InstanceKlass
4076 for (InstanceKlass* pv_node = previous_versions();
4077 pv_node != nullptr;
4078 pv_node = pv_node->previous_versions()) {
4079 if (!have_pv)
4080 st->print(BULLET"previous version: ");
4081 have_pv = true;
4082 pv_node->constants()->print_value_on(st);
4083 }
4084 if (have_pv) st->cr();
4085 }
4086
4087 print_on_maybe_null(st, BULLET"generic signature: ", generic_signature());
4088 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
4089 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();
4090 print_on_maybe_null(st, BULLET"record components: ", record_components());
4091 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();
4092 st->print(BULLET"loadable descriptors: "); loadable_descriptors()->print_value_on(st); st->cr();
4093 if (java_mirror() != nullptr) {
4094 st->print(BULLET"java mirror: ");
4095 java_mirror()->print_value_on(st);
4096 st->cr();
4097 } else {
4098 st->print_cr(BULLET"java mirror: null");
4099 }
4100 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
4101 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);
4102 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
4103 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(nullptr, start_of_itable(), itable_length(), st);
4104 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
4105
4106 FieldPrinter print_static_field(st);
4107 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
4108 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
4109 FieldPrinter print_nonstatic_field(st);
4110 InstanceKlass* ik = const_cast<InstanceKlass*>(this);
4111 ik->print_nonstatic_fields(&print_nonstatic_field);
4112
4113 st->print(BULLET"non-static oop maps (%d entries): ", nonstatic_oop_map_count());
4114 OopMapBlock* map = start_of_nonstatic_oop_maps();
4115 OopMapBlock* end_map = map + nonstatic_oop_map_count();
4116 while (map < end_map) {
4117 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
4118 map++;
4119 }
4120 st->cr();
4121
4122 if (fieldinfo_search_table() != nullptr) {
4123 st->print_cr(BULLET"---- field info search table:");
4124 FieldInfoStream::print_search_table(st, _constants, _fieldinfo_stream, _fieldinfo_search_table);
4125 }
4126 }
4127
4128 void InstanceKlass::print_value_on(outputStream* st) const {
4129 assert(is_klass(), "must be klass");
4130 if (Verbose || WizardMode) access_flags().print_on(st);
4131 name()->print_value_on(st);
4132 }
4133
4134 void FieldPrinter::do_field(fieldDescriptor* fd) {
4135 for (int i = 0; i < _indent; i++) _st->print(" ");
4136 _st->print(BULLET);
4137 if (_obj == nullptr) {
4138 fd->print_on(_st, _base_offset);
4139 _st->cr();
4140 } else {
4141 fd->print_on_for(_st, _obj, _indent, _base_offset);
4142 if (!fd->field_flags().is_flat()) _st->cr();
4143 }
4144 }
4145
4146
4147 void InstanceKlass::oop_print_on(oop obj, outputStream* st, int indent, int base_offset) {
4148 Klass::oop_print_on(obj, st);
4149
4150 if (this == vmClasses::String_klass()) {
4151 typeArrayOop value = java_lang_String::value(obj);
4152 juint length = java_lang_String::length(obj);
4153 if (value != nullptr &&
4154 value->is_typeArray() &&
4155 length <= (juint) value->length()) {
4156 st->print(BULLET"string: ");
4157 java_lang_String::print(obj, st);
4158 st->cr();
4159 }
4160 }
4161
4162 st->print_cr(BULLET"---- fields (total size %zu words):", oop_size(obj));
4163 FieldPrinter print_field(st, obj, indent, base_offset);
4164 print_nonstatic_fields(&print_field);
4165
4166 if (this == vmClasses::Class_klass()) {
4167 st->print(BULLET"signature: ");
4168 java_lang_Class::print_signature(obj, st);
4169 st->cr();
4170 Klass* real_klass = java_lang_Class::as_Klass(obj);
4171 if (real_klass != nullptr && real_klass->is_instance_klass()) {
4172 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj));
4173 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
4174 }
4175 } else if (this == vmClasses::MethodType_klass()) {
4176 st->print(BULLET"signature: ");
4177 java_lang_invoke_MethodType::print_signature(obj, st);
4178 st->cr();
4179 }
4180 }
4181
4182 #ifndef PRODUCT
4183
|