28 #include "cds/cdsEnumKlass.hpp"
29 #include "cds/classListWriter.hpp"
30 #include "cds/heapShared.hpp"
31 #include "cds/metaspaceShared.hpp"
32 #include "classfile/classFileParser.hpp"
33 #include "classfile/classFileStream.hpp"
34 #include "classfile/classLoader.hpp"
35 #include "classfile/classLoaderData.inline.hpp"
36 #include "classfile/javaClasses.hpp"
37 #include "classfile/moduleEntry.hpp"
38 #include "classfile/systemDictionary.hpp"
39 #include "classfile/systemDictionaryShared.hpp"
40 #include "classfile/verifier.hpp"
41 #include "classfile/vmClasses.hpp"
42 #include "classfile/vmSymbols.hpp"
43 #include "code/codeCache.hpp"
44 #include "code/dependencyContext.hpp"
45 #include "compiler/compilationPolicy.hpp"
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 "logging/log.hpp"
54 #include "logging/logMessage.hpp"
55 #include "logging/logStream.hpp"
56 #include "memory/allocation.inline.hpp"
57 #include "memory/iterator.inline.hpp"
58 #include "memory/metadataFactory.hpp"
59 #include "memory/metaspaceClosure.hpp"
60 #include "memory/oopFactory.hpp"
61 #include "memory/resourceArea.hpp"
62 #include "memory/universe.hpp"
63 #include "oops/fieldStreams.inline.hpp"
64 #include "oops/constantPool.hpp"
65 #include "oops/instanceClassLoaderKlass.hpp"
66 #include "oops/instanceKlass.inline.hpp"
67 #include "oops/instanceMirrorKlass.hpp"
68 #include "oops/instanceOop.hpp"
69 #include "oops/instanceStackChunkKlass.hpp"
70 #include "oops/klass.inline.hpp"
71 #include "oops/method.hpp"
72 #include "oops/oop.inline.hpp"
73 #include "oops/recordComponent.hpp"
74 #include "oops/symbol.hpp"
75 #include "prims/jvmtiExport.hpp"
76 #include "prims/jvmtiRedefineClasses.hpp"
77 #include "prims/jvmtiThreadState.hpp"
78 #include "prims/methodComparator.hpp"
79 #include "runtime/arguments.hpp"
80 #include "runtime/deoptimization.hpp"
81 #include "runtime/atomic.hpp"
82 #include "runtime/fieldDescriptor.inline.hpp"
83 #include "runtime/handles.inline.hpp"
84 #include "runtime/javaCalls.hpp"
85 #include "runtime/javaThread.inline.hpp"
86 #include "runtime/mutexLocker.hpp"
87 #include "runtime/orderAccess.hpp"
88 #include "runtime/os.inline.hpp"
89 #include "runtime/reflection.hpp"
90 #include "runtime/synchronizer.hpp"
91 #include "runtime/threads.hpp"
92 #include "services/classLoadingService.hpp"
93 #include "services/finalizerService.hpp"
94 #include "services/threadService.hpp"
571 if (local_interfaces != Universe::the_empty_instance_klass_array() &&
572 local_interfaces != nullptr && !local_interfaces->is_shared()) {
573 MetadataFactory::free_array<InstanceKlass*>(loader_data, local_interfaces);
574 }
575 }
576
577 void InstanceKlass::deallocate_record_components(ClassLoaderData* loader_data,
578 Array<RecordComponent*>* record_components) {
579 if (record_components != nullptr && !record_components->is_shared()) {
580 for (int i = 0; i < record_components->length(); i++) {
581 RecordComponent* record_component = record_components->at(i);
582 MetadataFactory::free_metadata(loader_data, record_component);
583 }
584 MetadataFactory::free_array<RecordComponent*>(loader_data, record_components);
585 }
586 }
587
588 // This function deallocates the metadata and C heap pointers that the
589 // InstanceKlass points to.
590 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
591 // Orphan the mirror first, CMS thinks it's still live.
592 if (java_mirror() != nullptr) {
593 java_lang_Class::set_klass(java_mirror(), nullptr);
594 }
595
596 // Also remove mirror from handles
597 loader_data->remove_handle(_java_mirror);
598
599 // Need to take this class off the class loader data list.
600 loader_data->remove_class(this);
601
602 // The array_klass for this class is created later, after error handling.
603 // For class redefinition, we keep the original class so this scratch class
604 // doesn't have an array class. Either way, assert that there is nothing
605 // to deallocate.
606 assert(array_klasses() == nullptr, "array classes shouldn't be created for this class yet");
607
608 // Release C heap allocated data that this points to, which includes
609 // reference counting symbol names.
610 // Can't release the constant pool or MethodData C heap data here because the constant
692 nest_members() != Universe::the_empty_short_array() &&
693 !nest_members()->is_shared()) {
694 MetadataFactory::free_array<jushort>(loader_data, nest_members());
695 }
696 set_nest_members(nullptr);
697
698 if (permitted_subclasses() != nullptr &&
699 permitted_subclasses() != Universe::the_empty_short_array() &&
700 !permitted_subclasses()->is_shared()) {
701 MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
702 }
703 set_permitted_subclasses(nullptr);
704
705 // We should deallocate the Annotations instance if it's not in shared spaces.
706 if (annotations() != nullptr && !annotations()->is_shared()) {
707 MetadataFactory::free_metadata(loader_data, annotations());
708 }
709 set_annotations(nullptr);
710
711 SystemDictionaryShared::handle_class_unloading(this);
712
713 #if INCLUDE_CDS_JAVA_HEAP
714 if (CDSConfig::is_dumping_heap()) {
715 HeapShared::remove_scratch_objects(this);
716 }
717 #endif
718 }
719
720 bool InstanceKlass::is_record() const {
721 return _record_components != nullptr &&
722 is_final() &&
723 java_super() == vmClasses::Record_klass();
724 }
725
726 bool InstanceKlass::is_sealed() const {
727 return _permitted_subclasses != nullptr &&
728 _permitted_subclasses != Universe::the_empty_short_array();
729 }
730
731 bool InstanceKlass::should_be_initialized() const {
732 return !is_initialized();
733 }
734
735 klassItable InstanceKlass::itable() const {
736 return klassItable(const_cast<InstanceKlass*>(this));
737 }
768 OrderAccess::storestore();
769 java_lang_Class::clear_init_lock(java_mirror());
770 assert(!is_not_initialized(), "class must be initialized now");
771 }
772
773
774 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
775 // process. The step comments refers to the procedure described in that section.
776 // Note: implementation moved to static method to expose the this pointer.
777 void InstanceKlass::initialize(TRAPS) {
778 if (this->should_be_initialized()) {
779 initialize_impl(CHECK);
780 // Note: at this point the class may be initialized
781 // OR it may be in the state of being initialized
782 // in case of recursive initialization!
783 } else {
784 assert(is_initialized(), "sanity check");
785 }
786 }
787
788
789 bool InstanceKlass::verify_code(TRAPS) {
790 // 1) Verify the bytecodes
791 return Verifier::verify(this, should_verify_class(), THREAD);
792 }
793
794 void InstanceKlass::link_class(TRAPS) {
795 assert(is_loaded(), "must be loaded");
796 if (!is_linked()) {
797 link_class_impl(CHECK);
798 }
799 }
800
801 // Called to verify that a class can link during initialization, without
802 // throwing a VerifyError.
803 bool InstanceKlass::link_class_or_fail(TRAPS) {
804 assert(is_loaded(), "must be loaded");
805 if (!is_linked()) {
806 link_class_impl(CHECK_false);
807 }
959 return true;
960 }
961
962 // Rewrite the byte codes of all of the methods of a class.
963 // The rewriter must be called exactly once. Rewriting must happen after
964 // verification but before the first method of the class is executed.
965 void InstanceKlass::rewrite_class(TRAPS) {
966 assert(is_loaded(), "must be loaded");
967 if (is_rewritten()) {
968 assert(is_shared(), "rewriting an unshared class?");
969 return;
970 }
971 Rewriter::rewrite(this, CHECK);
972 set_rewritten();
973 }
974
975 // Now relocate and link method entry points after class is rewritten.
976 // This is outside is_rewritten flag. In case of an exception, it can be
977 // executed more than once.
978 void InstanceKlass::link_methods(TRAPS) {
979 PerfTraceTime timer(ClassLoader::perf_ik_link_methods_time());
980
981 int len = methods()->length();
982 for (int i = len-1; i >= 0; i--) {
983 methodHandle m(THREAD, methods()->at(i));
984
985 // Set up method entry points for compiler and interpreter .
986 m->link_method(m, CHECK);
987 }
988 }
989
990 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
991 void InstanceKlass::initialize_super_interfaces(TRAPS) {
992 assert (has_nonstatic_concrete_methods(), "caller should have checked this");
993 for (int i = 0; i < local_interfaces()->length(); ++i) {
994 InstanceKlass* ik = local_interfaces()->at(i);
995
996 // Initialization is depth first search ie. we start with top of the inheritance tree
997 // has_nonstatic_concrete_methods drives searching superinterfaces since it
998 // means has_nonstatic_concrete_methods in its superinterface hierarchy
999 if (ik->has_nonstatic_concrete_methods()) {
1068 assert_locked_or_safepoint(ClassInitError_lock);
1069 InitErrorTableCleaner cleaner;
1070 if (_initialization_error_table != nullptr) {
1071 _initialization_error_table->unlink(&cleaner);
1072 }
1073 }
1074
1075 void InstanceKlass::initialize_impl(TRAPS) {
1076 HandleMark hm(THREAD);
1077
1078 // Make sure klass is linked (verified) before initialization
1079 // A class could already be verified, since it has been reflected upon.
1080 link_class(CHECK);
1081
1082 DTRACE_CLASSINIT_PROBE(required, -1);
1083
1084 bool wait = false;
1085
1086 JavaThread* jt = THREAD;
1087
1088 bool debug_logging_enabled = log_is_enabled(Debug, class, init);
1089
1090 // refer to the JVM book page 47 for description of steps
1091 // Step 1
1092 {
1093 Handle h_init_lock(THREAD, init_lock());
1094 ObjectLocker ol(h_init_lock, jt);
1095
1096 // Step 2
1097 // If we were to use wait() instead of waitInterruptibly() then
1098 // we might end up throwing IE from link/symbol resolution sites
1099 // that aren't expected to throw. This would wreak havoc. See 6320309.
1100 while (is_being_initialized() && !is_reentrant_initialization(jt)) {
1101 if (debug_logging_enabled) {
1102 ResourceMark rm(jt);
1103 log_debug(class, init)("Thread \"%s\" waiting for initialization of %s by thread \"%s\"",
1104 jt->name(), external_name(), init_thread_name());
1105 }
1106 wait = true;
1107 jt->set_class_to_be_initialized(this);
1206 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1207 ClassLoader::perf_class_init_selftime(),
1208 ClassLoader::perf_classes_inited(),
1209 jt->get_thread_stat()->perf_recursion_counts_addr(),
1210 jt->get_thread_stat()->perf_timers_addr(),
1211 PerfClassTraceTime::CLASS_CLINIT);
1212 call_class_initializer(THREAD);
1213 } else {
1214 // The elapsed time is so small it's not worth counting.
1215 if (UsePerfData) {
1216 ClassLoader::perf_classes_inited()->inc();
1217 }
1218 call_class_initializer(THREAD);
1219 }
1220 }
1221
1222 // Step 9
1223 if (!HAS_PENDING_EXCEPTION) {
1224 set_initialization_state_and_notify(fully_initialized, CHECK);
1225 debug_only(vtable().verify(tty, true);)
1226 }
1227 else {
1228 // Step 10 and 11
1229 Handle e(THREAD, PENDING_EXCEPTION);
1230 CLEAR_PENDING_EXCEPTION;
1231 // JVMTI has already reported the pending exception
1232 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1233 JvmtiExport::clear_detected_exception(jt);
1234 {
1235 EXCEPTION_MARK;
1236 add_initialization_error(THREAD, e);
1237 set_initialization_state_and_notify(initialization_error, THREAD);
1238 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1239 // JVMTI has already reported the pending exception
1240 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1241 JvmtiExport::clear_detected_exception(jt);
1242 }
1243 DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1244 if (e->is_a(vmClasses::Error_klass())) {
1245 THROW_OOP(e());
1246 } else {
1247 JavaCallArguments args(e);
1248 THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
1249 vmSymbols::throwable_void_signature(),
1250 &args);
1251 }
1252 }
1253 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1254 }
1255
1256
1257 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1258 Handle h_init_lock(THREAD, init_lock());
1259 if (h_init_lock() != nullptr) {
1260 ObjectLocker ol(h_init_lock, THREAD);
1261 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1262 set_init_state(state);
1263 fence_and_clear_init_lock();
1264 ol.notify_all(CHECK);
1265 } else {
1266 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1267 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1268 set_init_state(state);
1269 }
1270 }
1271
1272 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1273 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1274 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1275 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1276
1475 tty->print("Registered ");
1476 i->print_value_on(tty);
1477 tty->print_cr(" (" PTR_FORMAT ") as finalizable", p2i(i));
1478 }
1479 instanceHandle h_i(THREAD, i);
1480 // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1481 JavaValue result(T_VOID);
1482 JavaCallArguments args(h_i);
1483 methodHandle mh(THREAD, Universe::finalizer_register_method());
1484 JavaCalls::call(&result, mh, &args, CHECK_NULL);
1485 MANAGEMENT_ONLY(FinalizerService::on_register(h_i(), THREAD);)
1486 return h_i();
1487 }
1488
1489 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1490 assert(!is_abstract() && !is_interface(), "Should not create this object");
1491 size_t size = size_helper(); // Query before forming handle.
1492 return (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);
1493 }
1494
1495 instanceOop InstanceKlass::allocate_instance(oop java_class, TRAPS) {
1496 Klass* k = java_lang_Class::as_Klass(java_class);
1497 if (k == nullptr) {
1498 ResourceMark rm(THREAD);
1499 THROW_(vmSymbols::java_lang_InstantiationException(), nullptr);
1500 }
1501 InstanceKlass* ik = cast(k);
1502 ik->check_valid_for_instantiation(false, CHECK_NULL);
1503 ik->initialize(CHECK_NULL);
1504 return ik->allocate_instance(THREAD);
1505 }
1506
1507 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1508 return instanceHandle(THREAD, allocate_instance(THREAD));
1509 }
1510
1511 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1512 if (is_interface() || is_abstract()) {
1513 ResourceMark rm(THREAD);
1514 THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1515 : vmSymbols::java_lang_InstantiationException(), external_name());
1543 }
1544
1545 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1546 // Need load-acquire for lock-free read
1547 ObjArrayKlass* oak = array_klasses_acquire();
1548 if (oak == nullptr) {
1549 return nullptr;
1550 } else {
1551 return oak->array_klass_or_null(n);
1552 }
1553 }
1554
1555 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1556 return array_klass(1, THREAD);
1557 }
1558
1559 ArrayKlass* InstanceKlass::array_klass_or_null() {
1560 return array_klass_or_null(1);
1561 }
1562
1563 static int call_class_initializer_counter = 0; // for debugging
1564
1565 Method* InstanceKlass::class_initializer() const {
1566 Method* clinit = find_method(
1567 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1568 if (clinit != nullptr && clinit->has_valid_initializer_flags()) {
1569 return clinit;
1570 }
1571 return nullptr;
1572 }
1573
1574 void InstanceKlass::call_class_initializer(TRAPS) {
1575 if (ReplayCompiles &&
1576 (ReplaySuppressInitializers == 1 ||
1577 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1578 // Hide the existence of the initializer for the purpose of replaying the compile
1579 return;
1580 }
1581
1582 #if INCLUDE_CDS
1583 // This is needed to ensure the consistency of the archived heap objects.
1584 if (has_archived_enum_objs()) {
1585 assert(is_shared(), "must be");
1586 bool initialized = CDSEnumKlass::initialize_enum_klass(this, CHECK);
1587 if (initialized) {
1588 return;
1589 }
1590 }
1591 #endif
1592
1593 methodHandle h_method(THREAD, class_initializer());
1594 assert(!is_initialized(), "we cannot initialize twice");
1595 LogTarget(Info, class, init) lt;
1596 if (lt.is_enabled()) {
1597 ResourceMark rm(THREAD);
1598 LogStream ls(lt);
1599 ls.print("%d Initializing ", call_class_initializer_counter++);
1600 name()->print_value_on(&ls);
1601 ls.print_cr("%s (" PTR_FORMAT ") by thread \"%s\"",
1602 h_method() == nullptr ? "(no method)" : "", p2i(this),
1603 THREAD->name());
1604 }
1605 if (h_method() != nullptr) {
1606 JavaCallArguments args; // No arguments
1607 JavaValue result(T_VOID);
1608 JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1609 }
1610 }
1611
1612
1613 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1614 InterpreterOopMap* entry_for) {
1615 // Lazily create the _oop_map_cache at first request.
1616 // Load_acquire is needed to safely get instance published with CAS by another thread.
1617 OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache);
1618 if (oop_map_cache == nullptr) {
1619 // Try to install new instance atomically.
1620 oop_map_cache = new OopMapCache();
1621 OopMapCache* other = Atomic::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
1622 if (other != nullptr) {
1623 // Someone else managed to install before us, ditch local copy and use the existing one.
1624 delete oop_map_cache;
1625 oop_map_cache = other;
1626 }
1627 }
1628 // _oop_map_cache is constant after init; lookup below does its own locking.
1629 oop_map_cache->lookup(method, bci, entry_for);
1630 }
1631
1632 bool InstanceKlass::contains_field_offset(int offset) {
2353 }
2354 }
2355 if (new_jmeths != 0) {
2356 Method::ensure_jmethod_ids(class_loader_data(), new_jmeths);
2357 }
2358 }
2359
2360 // Lookup a jmethodID, null if not found. Do no blocking, no allocations, no handles
2361 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
2362 int idnum = method->method_idnum();
2363 jmethodID* jmeths = methods_jmethod_ids_acquire();
2364 return (jmeths != nullptr) ? jmeths[idnum + 1] : nullptr;
2365 }
2366
2367 inline DependencyContext InstanceKlass::dependencies() {
2368 DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);
2369 return dep_context;
2370 }
2371
2372 void InstanceKlass::mark_dependent_nmethods(DeoptimizationScope* deopt_scope, KlassDepChange& changes) {
2373 dependencies().mark_dependent_nmethods(deopt_scope, changes);
2374 }
2375
2376 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2377 dependencies().add_dependent_nmethod(nm);
2378 }
2379
2380 void InstanceKlass::clean_dependency_context() {
2381 dependencies().clean_unloading_dependents();
2382 }
2383
2384 #ifndef PRODUCT
2385 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2386 dependencies().print_dependent_nmethods(verbose);
2387 }
2388
2389 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2390 return dependencies().is_dependent_nmethod(nm);
2391 }
2392 #endif //PRODUCT
2393
2482 if (itable_length() > 0) {
2483 itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2484 int method_table_offset_in_words = ioe->offset()/wordSize;
2485 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2486
2487 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2488 / itableOffsetEntry::size();
2489
2490 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2491 if (ioe->interface_klass() != nullptr) {
2492 it->push(ioe->interface_klass_addr());
2493 itableMethodEntry* ime = ioe->first_method_entry(this);
2494 int n = klassItable::method_count_for_interface(ioe->interface_klass());
2495 for (int index = 0; index < n; index ++) {
2496 it->push(ime[index].method_addr());
2497 }
2498 }
2499 }
2500 }
2501
2502 it->push(&_nest_members);
2503 it->push(&_permitted_subclasses);
2504 it->push(&_record_components);
2505 }
2506
2507 #if INCLUDE_CDS
2508 void InstanceKlass::remove_unshareable_info() {
2509
2510 if (is_linked()) {
2511 assert(can_be_verified_at_dumptime(), "must be");
2512 // Remember this so we can avoid walking the hierarchy at runtime.
2513 set_verified_at_dump_time();
2514 }
2515
2516 Klass::remove_unshareable_info();
2517
2518 if (SystemDictionaryShared::has_class_failed_verification(this)) {
2519 // Classes are attempted to link during dumping and may fail,
2520 // but these classes are still in the dictionary and class list in CLD.
2521 // If the class has failed verification, there is nothing else to remove.
2522 return;
2523 }
2524
2525 // Reset to the 'allocated' state to prevent any premature accessing to
2526 // a shared class at runtime while the class is still being loaded and
2527 // restored. A class' init_state is set to 'loaded' at runtime when it's
2528 // being added to class hierarchy (see InstanceKlass:::add_to_hierarchy()).
2529 _init_state = allocated;
2530
2531 { // Otherwise this needs to take out the Compile_lock.
2532 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2533 init_implementor();
2534 }
2545 // do array classes also.
2546 if (array_klasses() != nullptr) {
2547 array_klasses()->remove_unshareable_info();
2548 }
2549
2550 // These are not allocated from metaspace. They are safe to set to null.
2551 _source_debug_extension = nullptr;
2552 _dep_context = nullptr;
2553 _osr_nmethods_head = nullptr;
2554 #if INCLUDE_JVMTI
2555 _breakpoints = nullptr;
2556 _previous_versions = nullptr;
2557 _cached_class_file = nullptr;
2558 _jvmti_cached_class_field_map = nullptr;
2559 #endif
2560
2561 _init_thread = nullptr;
2562 _methods_jmethod_ids = nullptr;
2563 _jni_ids = nullptr;
2564 _oop_map_cache = nullptr;
2565 // clear _nest_host to ensure re-load at runtime
2566 _nest_host = nullptr;
2567 init_shared_package_entry();
2568 _dep_context_last_cleaned = 0;
2569
2570 remove_unshareable_flags();
2571 }
2572
2573 void InstanceKlass::remove_unshareable_flags() {
2574 // clear all the flags/stats that shouldn't be in the archived version
2575 assert(!is_scratch_class(), "must be");
2576 assert(!has_been_redefined(), "must be");
2577 #if INCLUDE_JVMTI
2578 set_is_being_redefined(false);
2579 #endif
2580 set_has_resolved_methods(false);
2581 }
2582
2583 void InstanceKlass::remove_java_mirror() {
2584 Klass::remove_java_mirror();
2585
2586 // do array classes also.
2587 if (array_klasses() != nullptr) {
2588 array_klasses()->remove_java_mirror();
2654
2655 // restore constant pool resolved references
2656 constants()->restore_unshareable_info(CHECK);
2657
2658 if (array_klasses() != nullptr) {
2659 // To get a consistent list of classes we need MultiArray_lock to ensure
2660 // array classes aren't observed while they are being restored.
2661 RecursiveLocker rl(MultiArray_lock, THREAD);
2662 assert(this == array_klasses()->bottom_klass(), "sanity");
2663 // Array classes have null protection domain.
2664 // --> see ArrayKlass::complete_create_array_klass()
2665 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
2666 }
2667
2668 // Initialize @ValueBased class annotation if not already set in the archived klass.
2669 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
2670 set_is_value_based();
2671 }
2672 }
2673
2674 // Check if a class or any of its supertypes has a version older than 50.
2675 // CDS will not perform verification of old classes during dump time because
2676 // without changing the old verifier, the verification constraint cannot be
2677 // retrieved during dump time.
2678 // Verification of archived old classes will be performed during run time.
2679 bool InstanceKlass::can_be_verified_at_dumptime() const {
2680 if (MetaspaceShared::is_in_shared_metaspace(this)) {
2681 // This is a class that was dumped into the base archive, so we know
2682 // it was verified at dump time.
2683 return true;
2684 }
2685 if (major_version() < 50 /*JAVA_6_VERSION*/) {
2686 return false;
2687 }
2688 if (java_super() != nullptr && !java_super()->can_be_verified_at_dumptime()) {
2689 return false;
2690 }
2691 Array<InstanceKlass*>* interfaces = local_interfaces();
2692 int len = interfaces->length();
2693 for (int i = 0; i < len; i++) {
2694 if (!interfaces->at(i)->can_be_verified_at_dumptime()) {
2695 return false;
2696 }
2697 }
2698 return true;
2699 }
2700
2701 bool InstanceKlass::methods_contain_jsr_bytecode() const {
2702 Thread* thread = Thread::current();
2703 for (int i = 0; i < _methods->length(); i++) {
2704 methodHandle m(thread, _methods->at(i));
2705 BytecodeStream bcs(m);
2706 while (!bcs.is_last_bytecode()) {
2707 Bytecodes::Code opcode = bcs.next();
2708 if (opcode == Bytecodes::_jsr || opcode == Bytecodes::_jsr_w) {
2709 return true;
2710 }
2711 }
2712 }
2713 return false;
2714 }
2715 #endif // INCLUDE_CDS
2716
2717 #if INCLUDE_JVMTI
2718 static void clear_all_breakpoints(Method* m) {
2719 m->clear_all_breakpoints();
2720 }
2721 #endif
2722
2723 void InstanceKlass::unload_class(InstanceKlass* ik) {
2724
2725 if (ik->is_scratch_class()) {
2726 assert(ik->dependencies().is_empty(), "dependencies should be empty for scratch classes");
2727 return;
2728 }
2729 assert(ik->is_loaded(), "class should be loaded " PTR_FORMAT, p2i(ik));
2730
2731 // Release dependencies.
2732 ik->dependencies().remove_all_dependents();
2733
2734 // notify the debugger
3468 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3469 for (int i = 0; i < len; i++) {
3470 intptr_t e = start[i];
3471 st->print("%d : " INTPTR_FORMAT, i, e);
3472 if (MetaspaceObj::is_valid((Metadata*)e)) {
3473 st->print(" ");
3474 ((Metadata*)e)->print_value_on(st);
3475 }
3476 st->cr();
3477 }
3478 }
3479
3480 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3481 return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3482 }
3483
3484 const char* InstanceKlass::init_state_name() const {
3485 return state_names[init_state()];
3486 }
3487
3488 void InstanceKlass::print_on(outputStream* st) const {
3489 assert(is_klass(), "must be klass");
3490 Klass::print_on(st);
3491
3492 st->print(BULLET"instance size: %d", size_helper()); st->cr();
3493 st->print(BULLET"klass size: %d", size()); st->cr();
3494 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
3495 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
3496 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
3497 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
3498 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3499 st->print(BULLET"sub: ");
3500 Klass* sub = subklass();
3501 int n;
3502 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3503 if (n < MaxSubklassPrintSize) {
3504 sub->print_value_on(st);
3505 st->print(" ");
3506 }
3507 }
3797 nullptr;
3798 // caller can be null, for example, during a JVMTI VM_Init hook
3799 if (caller != nullptr) {
3800 info_stream.print(" source: instance of %s", caller->external_name());
3801 } else {
3802 // source is unknown
3803 }
3804 } else {
3805 oop class_loader = loader_data->class_loader();
3806 info_stream.print(" source: %s", class_loader->klass()->external_name());
3807 }
3808 } else {
3809 assert(this->is_shared(), "must be");
3810 if (MetaspaceShared::is_shared_dynamic((void*)this)) {
3811 info_stream.print(" source: shared objects file (top)");
3812 } else {
3813 info_stream.print(" source: shared objects file");
3814 }
3815 }
3816
3817 msg.info("%s", info_stream.as_string());
3818
3819 if (log_is_enabled(Debug, class, load)) {
3820 stringStream debug_stream;
3821
3822 // Class hierarchy info
3823 debug_stream.print(" klass: " PTR_FORMAT " super: " PTR_FORMAT,
3824 p2i(this), p2i(superklass()));
3825
3826 // Interfaces
3827 if (local_interfaces() != nullptr && local_interfaces()->length() > 0) {
3828 debug_stream.print(" interfaces:");
3829 int length = local_interfaces()->length();
3830 for (int i = 0; i < length; i++) {
3831 debug_stream.print(" " PTR_FORMAT,
3832 p2i(InstanceKlass::cast(local_interfaces()->at(i))));
3833 }
3834 }
3835
3836 // Class loader
|
28 #include "cds/cdsEnumKlass.hpp"
29 #include "cds/classListWriter.hpp"
30 #include "cds/heapShared.hpp"
31 #include "cds/metaspaceShared.hpp"
32 #include "classfile/classFileParser.hpp"
33 #include "classfile/classFileStream.hpp"
34 #include "classfile/classLoader.hpp"
35 #include "classfile/classLoaderData.inline.hpp"
36 #include "classfile/javaClasses.hpp"
37 #include "classfile/moduleEntry.hpp"
38 #include "classfile/systemDictionary.hpp"
39 #include "classfile/systemDictionaryShared.hpp"
40 #include "classfile/verifier.hpp"
41 #include "classfile/vmClasses.hpp"
42 #include "classfile/vmSymbols.hpp"
43 #include "code/codeCache.hpp"
44 #include "code/dependencyContext.hpp"
45 #include "compiler/compilationPolicy.hpp"
46 #include "compiler/compileBroker.hpp"
47 #include "gc/shared/collectedHeap.inline.hpp"
48 #include "interpreter/bytecodeHistogram.hpp"
49 #include "interpreter/bytecodeStream.hpp"
50 #include "interpreter/oopMapCache.hpp"
51 #include "interpreter/rewriter.hpp"
52 #include "jvm.h"
53 #include "jvmtifiles/jvmti.h"
54 #include "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/fieldStreams.inline.hpp"
65 #include "oops/constantPool.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 "oops/trainingData.hpp"
77 #include "prims/jvmtiExport.hpp"
78 #include "prims/jvmtiRedefineClasses.hpp"
79 #include "prims/jvmtiThreadState.hpp"
80 #include "prims/methodComparator.hpp"
81 #include "runtime/arguments.hpp"
82 #include "runtime/deoptimization.hpp"
83 #include "runtime/atomic.hpp"
84 #include "runtime/fieldDescriptor.inline.hpp"
85 #include "runtime/handles.inline.hpp"
86 #include "runtime/javaCalls.hpp"
87 #include "runtime/javaThread.inline.hpp"
88 #include "runtime/mutexLocker.hpp"
89 #include "runtime/orderAccess.hpp"
90 #include "runtime/os.inline.hpp"
91 #include "runtime/reflection.hpp"
92 #include "runtime/synchronizer.hpp"
93 #include "runtime/threads.hpp"
94 #include "services/classLoadingService.hpp"
95 #include "services/finalizerService.hpp"
96 #include "services/threadService.hpp"
573 if (local_interfaces != Universe::the_empty_instance_klass_array() &&
574 local_interfaces != nullptr && !local_interfaces->is_shared()) {
575 MetadataFactory::free_array<InstanceKlass*>(loader_data, local_interfaces);
576 }
577 }
578
579 void InstanceKlass::deallocate_record_components(ClassLoaderData* loader_data,
580 Array<RecordComponent*>* record_components) {
581 if (record_components != nullptr && !record_components->is_shared()) {
582 for (int i = 0; i < record_components->length(); i++) {
583 RecordComponent* record_component = record_components->at(i);
584 MetadataFactory::free_metadata(loader_data, record_component);
585 }
586 MetadataFactory::free_array<RecordComponent*>(loader_data, record_components);
587 }
588 }
589
590 // This function deallocates the metadata and C heap pointers that the
591 // InstanceKlass points to.
592 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
593 #if INCLUDE_CDS_JAVA_HEAP
594 if (CDSConfig::is_dumping_heap()) {
595 HeapShared::remove_scratch_objects(this);
596 }
597 #endif
598
599 // Orphan the mirror first, CMS thinks it's still live.
600 if (java_mirror() != nullptr) {
601 java_lang_Class::set_klass(java_mirror(), nullptr);
602 }
603
604 // Also remove mirror from handles
605 loader_data->remove_handle(_java_mirror);
606
607 // Need to take this class off the class loader data list.
608 loader_data->remove_class(this);
609
610 // The array_klass for this class is created later, after error handling.
611 // For class redefinition, we keep the original class so this scratch class
612 // doesn't have an array class. Either way, assert that there is nothing
613 // to deallocate.
614 assert(array_klasses() == nullptr, "array classes shouldn't be created for this class yet");
615
616 // Release C heap allocated data that this points to, which includes
617 // reference counting symbol names.
618 // Can't release the constant pool or MethodData C heap data here because the constant
700 nest_members() != Universe::the_empty_short_array() &&
701 !nest_members()->is_shared()) {
702 MetadataFactory::free_array<jushort>(loader_data, nest_members());
703 }
704 set_nest_members(nullptr);
705
706 if (permitted_subclasses() != nullptr &&
707 permitted_subclasses() != Universe::the_empty_short_array() &&
708 !permitted_subclasses()->is_shared()) {
709 MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
710 }
711 set_permitted_subclasses(nullptr);
712
713 // We should deallocate the Annotations instance if it's not in shared spaces.
714 if (annotations() != nullptr && !annotations()->is_shared()) {
715 MetadataFactory::free_metadata(loader_data, annotations());
716 }
717 set_annotations(nullptr);
718
719 SystemDictionaryShared::handle_class_unloading(this);
720 }
721
722 bool InstanceKlass::is_record() const {
723 return _record_components != nullptr &&
724 is_final() &&
725 java_super() == vmClasses::Record_klass();
726 }
727
728 bool InstanceKlass::is_sealed() const {
729 return _permitted_subclasses != nullptr &&
730 _permitted_subclasses != Universe::the_empty_short_array();
731 }
732
733 bool InstanceKlass::should_be_initialized() const {
734 return !is_initialized();
735 }
736
737 klassItable InstanceKlass::itable() const {
738 return klassItable(const_cast<InstanceKlass*>(this));
739 }
770 OrderAccess::storestore();
771 java_lang_Class::clear_init_lock(java_mirror());
772 assert(!is_not_initialized(), "class must be initialized now");
773 }
774
775
776 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
777 // process. The step comments refers to the procedure described in that section.
778 // Note: implementation moved to static method to expose the this pointer.
779 void InstanceKlass::initialize(TRAPS) {
780 if (this->should_be_initialized()) {
781 initialize_impl(CHECK);
782 // Note: at this point the class may be initialized
783 // OR it may be in the state of being initialized
784 // in case of recursive initialization!
785 } else {
786 assert(is_initialized(), "sanity check");
787 }
788 }
789
790 static bool are_super_types_initialized(InstanceKlass* ik) {
791 InstanceKlass* s = ik->java_super();
792 if (s != nullptr && !s->is_initialized()) {
793 if (log_is_enabled(Info, cds, init)) {
794 ResourceMark rm;
795 log_info(cds, init)("%s takes slow path because super class %s is not initialized",
796 ik->external_name(), s->external_name());
797 }
798 return false;
799 }
800
801 if (ik->has_nonstatic_concrete_methods()) {
802 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
803 // having a superinterface that declares, non-static, concrete methods
804 Array<InstanceKlass*>* interfaces = ik->local_interfaces();
805 int len = interfaces->length();
806 for (int i = 0; i < len; i++) {
807 InstanceKlass* intf = interfaces->at(i);
808 if (!intf->is_initialized()) {
809 if (log_is_enabled(Info, cds, init)) {
810 ResourceMark rm;
811 log_info(cds, init)("%s takes slow path because interface %s is not initialized",
812 ik->external_name(), intf->external_name());
813 }
814 return false;
815 }
816 }
817 }
818
819 return true;
820 }
821
822 static void log_class_init_start(outputStream* st, JavaThread* current, InstanceKlass* ik, int init_id) {
823 ResourceMark rm;
824 const char* info = "";
825 if (ik->has_preinitialized_mirror() && CDSConfig::is_loading_heap()) {
826 info = " (preinitialized)";
827 } else if (ik->class_initializer() == nullptr) {
828 info = " (no method)";
829 }
830 st->print("%d Initializing ", init_id);
831 ik->name()->print_value_on(st);
832 st->print_cr("%s (" PTR_FORMAT ") by thread " PTR_FORMAT " \"%s\"", info, p2i(ik), p2i(current), current->name());
833 }
834
835 static int log_class_init(JavaThread* current, InstanceKlass* ik) {
836 int init_id = -1;
837 LogStreamHandle(Info, init, class) lsh1;
838 LogStreamHandle(Debug, init) lsh2;
839 if (lsh1.is_enabled() || lsh2.is_enabled()) {
840 static int call_class_initializer_counter = 0; // for debugging
841 init_id = Atomic::fetch_then_add(&call_class_initializer_counter, 1);
842 if (lsh1.is_enabled()) {
843 log_class_init_start(&lsh1, current, ik, init_id);
844 }
845 if (lsh2.is_enabled() && ik->class_initializer() != nullptr && !ik->has_preinitialized_mirror()) {
846 log_class_init_start(&lsh2, current, ik, init_id);
847 }
848 }
849 return init_id;
850 }
851
852 void InstanceKlass::initialize_from_cds(TRAPS) {
853 if (is_initialized()) {
854 return;
855 }
856
857 if (has_preinitialized_mirror() && CDSConfig::is_loading_heap() &&
858 !ForceProfiling &&
859 !RecordTraining &&
860 are_super_types_initialized(this)) {
861 // FIXME: also check for events listeners such as JVMTI, JFR, etc
862 if (log_is_enabled(Info, cds, init)) {
863 ResourceMark rm;
864 log_info(cds, init)("%s (quickest)", external_name());
865 }
866
867 link_class(CHECK);
868
869 #ifdef AZZERT
870 {
871 MonitorLocker ml(THREAD, _init_monitor);
872 assert(!initialized(), "sanity");
873 assert(!is_being_initialized(), "sanity");
874 assert(!is_in_error_state(), "sanity");
875 }
876 #endif
877
878 log_class_init(THREAD, this);
879 set_init_thread(THREAD);
880 set_initialization_state_and_notify(fully_initialized, CHECK);
881 return;
882 }
883
884 if (log_is_enabled(Info, cds, init)) {
885 ResourceMark rm;
886 log_info(cds, init)("%s%s", external_name(),
887 (has_preinitialized_mirror() && CDSConfig::is_loading_heap()) ? " (quicker)" : "");
888 }
889 initialize(THREAD);
890 }
891
892 bool InstanceKlass::verify_code(TRAPS) {
893 // 1) Verify the bytecodes
894 return Verifier::verify(this, should_verify_class(), THREAD);
895 }
896
897 void InstanceKlass::link_class(TRAPS) {
898 assert(is_loaded(), "must be loaded");
899 if (!is_linked()) {
900 link_class_impl(CHECK);
901 }
902 }
903
904 // Called to verify that a class can link during initialization, without
905 // throwing a VerifyError.
906 bool InstanceKlass::link_class_or_fail(TRAPS) {
907 assert(is_loaded(), "must be loaded");
908 if (!is_linked()) {
909 link_class_impl(CHECK_false);
910 }
1062 return true;
1063 }
1064
1065 // Rewrite the byte codes of all of the methods of a class.
1066 // The rewriter must be called exactly once. Rewriting must happen after
1067 // verification but before the first method of the class is executed.
1068 void InstanceKlass::rewrite_class(TRAPS) {
1069 assert(is_loaded(), "must be loaded");
1070 if (is_rewritten()) {
1071 assert(is_shared(), "rewriting an unshared class?");
1072 return;
1073 }
1074 Rewriter::rewrite(this, CHECK);
1075 set_rewritten();
1076 }
1077
1078 // Now relocate and link method entry points after class is rewritten.
1079 // This is outside is_rewritten flag. In case of an exception, it can be
1080 // executed more than once.
1081 void InstanceKlass::link_methods(TRAPS) {
1082 PerfTraceElapsedTime timer(ClassLoader::perf_ik_link_methods_time());
1083
1084 int len = methods()->length();
1085 for (int i = len-1; i >= 0; i--) {
1086 methodHandle m(THREAD, methods()->at(i));
1087
1088 // Set up method entry points for compiler and interpreter .
1089 m->link_method(m, CHECK);
1090 }
1091 }
1092
1093 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
1094 void InstanceKlass::initialize_super_interfaces(TRAPS) {
1095 assert (has_nonstatic_concrete_methods(), "caller should have checked this");
1096 for (int i = 0; i < local_interfaces()->length(); ++i) {
1097 InstanceKlass* ik = local_interfaces()->at(i);
1098
1099 // Initialization is depth first search ie. we start with top of the inheritance tree
1100 // has_nonstatic_concrete_methods drives searching superinterfaces since it
1101 // means has_nonstatic_concrete_methods in its superinterface hierarchy
1102 if (ik->has_nonstatic_concrete_methods()) {
1171 assert_locked_or_safepoint(ClassInitError_lock);
1172 InitErrorTableCleaner cleaner;
1173 if (_initialization_error_table != nullptr) {
1174 _initialization_error_table->unlink(&cleaner);
1175 }
1176 }
1177
1178 void InstanceKlass::initialize_impl(TRAPS) {
1179 HandleMark hm(THREAD);
1180
1181 // Make sure klass is linked (verified) before initialization
1182 // A class could already be verified, since it has been reflected upon.
1183 link_class(CHECK);
1184
1185 DTRACE_CLASSINIT_PROBE(required, -1);
1186
1187 bool wait = false;
1188
1189 JavaThread* jt = THREAD;
1190
1191 if (ForceProfiling) {
1192 // Preallocate MDOs.
1193 for (int i = 0; i < methods()->length(); i++) {
1194 assert(!HAS_PENDING_EXCEPTION, "");
1195 methodHandle m(THREAD, methods()->at(i));
1196 Method::build_profiling_method_data(m, THREAD);
1197 if (HAS_PENDING_EXCEPTION) {
1198 ResourceMark rm;
1199 log_warning(cds)("MDO preallocation failed for %s", external_name());
1200 CLEAR_PENDING_EXCEPTION;
1201 break;
1202 }
1203 }
1204 }
1205
1206 bool debug_logging_enabled = log_is_enabled(Debug, class, init);
1207
1208 // refer to the JVM book page 47 for description of steps
1209 // Step 1
1210 {
1211 Handle h_init_lock(THREAD, init_lock());
1212 ObjectLocker ol(h_init_lock, jt);
1213
1214 // Step 2
1215 // If we were to use wait() instead of waitInterruptibly() then
1216 // we might end up throwing IE from link/symbol resolution sites
1217 // that aren't expected to throw. This would wreak havoc. See 6320309.
1218 while (is_being_initialized() && !is_reentrant_initialization(jt)) {
1219 if (debug_logging_enabled) {
1220 ResourceMark rm(jt);
1221 log_debug(class, init)("Thread \"%s\" waiting for initialization of %s by thread \"%s\"",
1222 jt->name(), external_name(), init_thread_name());
1223 }
1224 wait = true;
1225 jt->set_class_to_be_initialized(this);
1324 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1325 ClassLoader::perf_class_init_selftime(),
1326 ClassLoader::perf_classes_inited(),
1327 jt->get_thread_stat()->perf_recursion_counts_addr(),
1328 jt->get_thread_stat()->perf_timers_addr(),
1329 PerfClassTraceTime::CLASS_CLINIT);
1330 call_class_initializer(THREAD);
1331 } else {
1332 // The elapsed time is so small it's not worth counting.
1333 if (UsePerfData) {
1334 ClassLoader::perf_classes_inited()->inc();
1335 }
1336 call_class_initializer(THREAD);
1337 }
1338 }
1339
1340 // Step 9
1341 if (!HAS_PENDING_EXCEPTION) {
1342 set_initialization_state_and_notify(fully_initialized, CHECK);
1343 debug_only(vtable().verify(tty, true);)
1344 CompilationPolicy::replay_training_at_init(this, THREAD);
1345 }
1346 else {
1347 // Step 10 and 11
1348 Handle e(THREAD, PENDING_EXCEPTION);
1349 CLEAR_PENDING_EXCEPTION;
1350 // JVMTI has already reported the pending exception
1351 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1352 JvmtiExport::clear_detected_exception(jt);
1353 {
1354 EXCEPTION_MARK;
1355 add_initialization_error(THREAD, e);
1356 set_initialization_state_and_notify(initialization_error, THREAD);
1357 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1358 // JVMTI has already reported the pending exception
1359 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1360 JvmtiExport::clear_detected_exception(jt);
1361 }
1362 DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1363 if (e->is_a(vmClasses::Error_klass())) {
1364 THROW_OOP(e());
1365 } else {
1366 JavaCallArguments args(e);
1367 THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
1368 vmSymbols::throwable_void_signature(),
1369 &args);
1370 }
1371 }
1372 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1373 }
1374
1375 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1376 Handle h_init_lock(THREAD, init_lock());
1377 if (h_init_lock() != nullptr) {
1378 ObjectLocker ol(h_init_lock, THREAD);
1379 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1380 set_init_state(state);
1381 fence_and_clear_init_lock();
1382 ol.notify_all(CHECK);
1383 } else {
1384 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1385 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1386 set_init_state(state);
1387 }
1388 }
1389
1390 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1391 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1392 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1393 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1394
1593 tty->print("Registered ");
1594 i->print_value_on(tty);
1595 tty->print_cr(" (" PTR_FORMAT ") as finalizable", p2i(i));
1596 }
1597 instanceHandle h_i(THREAD, i);
1598 // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1599 JavaValue result(T_VOID);
1600 JavaCallArguments args(h_i);
1601 methodHandle mh(THREAD, Universe::finalizer_register_method());
1602 JavaCalls::call(&result, mh, &args, CHECK_NULL);
1603 MANAGEMENT_ONLY(FinalizerService::on_register(h_i(), THREAD);)
1604 return h_i();
1605 }
1606
1607 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1608 assert(!is_abstract() && !is_interface(), "Should not create this object");
1609 size_t size = size_helper(); // Query before forming handle.
1610 return (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);
1611 }
1612
1613 instanceOop InstanceKlass::allocate_instance(oop java_class,
1614 const char* who,
1615 TRAPS) {
1616 Klass* k = java_lang_Class::as_Klass(java_class);
1617 if (k == nullptr) {
1618 ResourceMark rm(THREAD);
1619 THROW_(vmSymbols::java_lang_InstantiationException(), nullptr);
1620 }
1621 InstanceKlass* ik = cast(k);
1622 ik->check_valid_for_instantiation(false, CHECK_NULL);
1623 ik->initialize(CHECK_NULL);
1624 return ik->allocate_instance(THREAD);
1625 }
1626
1627 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1628 return instanceHandle(THREAD, allocate_instance(THREAD));
1629 }
1630
1631 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1632 if (is_interface() || is_abstract()) {
1633 ResourceMark rm(THREAD);
1634 THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1635 : vmSymbols::java_lang_InstantiationException(), external_name());
1663 }
1664
1665 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1666 // Need load-acquire for lock-free read
1667 ObjArrayKlass* oak = array_klasses_acquire();
1668 if (oak == nullptr) {
1669 return nullptr;
1670 } else {
1671 return oak->array_klass_or_null(n);
1672 }
1673 }
1674
1675 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1676 return array_klass(1, THREAD);
1677 }
1678
1679 ArrayKlass* InstanceKlass::array_klass_or_null() {
1680 return array_klass_or_null(1);
1681 }
1682
1683 Method* InstanceKlass::class_initializer() const {
1684 Method* clinit = find_method(
1685 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1686 if (clinit != nullptr && clinit->has_valid_initializer_flags()) {
1687 return clinit;
1688 }
1689 return nullptr;
1690 }
1691
1692 void InstanceKlass::call_class_initializer(TRAPS) {
1693 if (ReplayCompiles &&
1694 (ReplaySuppressInitializers == 1 ||
1695 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1696 // Hide the existence of the initializer for the purpose of replaying the compile
1697 return;
1698 }
1699
1700 #if INCLUDE_CDS
1701 // This is needed to ensure the consistency of the archived heap objects.
1702 if (has_archived_enum_objs()) {
1703 assert(is_shared(), "must be");
1704 bool initialized = CDSEnumKlass::initialize_enum_klass(this, CHECK);
1705 if (initialized) {
1706 return;
1707 }
1708 } else if (has_preinitialized_mirror() && CDSConfig::is_loading_heap()) {
1709 log_class_init(THREAD, this);
1710 return;
1711 }
1712 #endif
1713
1714 methodHandle h_method(THREAD, class_initializer());
1715 assert(!is_initialized(), "we cannot initialize twice");
1716 int init_id = log_class_init(THREAD, this);
1717 if (h_method() != nullptr) {
1718 JavaCallArguments args; // No arguments
1719 JavaValue result(T_VOID);
1720 InstanceKlass* outer = THREAD->set_class_being_initialized(this);
1721 jlong bc_start = (CountBytecodesPerThread ? THREAD->bc_counter_value() : BytecodeCounter::counter_value());
1722
1723 elapsedTimer timer;
1724 {
1725 PerfPauseTimer pt(THREAD->current_rt_call_timer(), THREAD->profile_rt_calls());
1726 PauseRuntimeCallProfiling prcp(THREAD, THREAD->profile_rt_calls());
1727
1728 timer.start();
1729 JavaCalls::call(&result, h_method, &args, THREAD); // Static call (no args)
1730 timer.stop();
1731 }
1732
1733 jlong bc_end = (CountBytecodesPerThread ? THREAD->bc_counter_value() : BytecodeCounter::counter_value());
1734
1735 jlong bc_executed = (bc_end - bc_start);
1736 if (UsePerfData && outer == nullptr) { // outermost clinit
1737 THREAD->inc_clinit_bc_counter_value(bc_executed);
1738 ClassLoader::perf_class_init_bytecodes_count()->inc(bc_executed);
1739 }
1740
1741 THREAD->set_class_being_initialized(outer);
1742
1743 LogStreamHandle(Debug, init) log;
1744 if (log.is_enabled()) {
1745 ResourceMark rm(THREAD);
1746 log.print("%d Initialized in %.3fms (total: " JLONG_FORMAT "ms); ",
1747 init_id, timer.seconds() * 1000.0, ClassLoader::class_init_time_ms());
1748 if (CountBytecodes || CountBytecodesPerThread) {
1749 log.print("executed " JLONG_FORMAT " bytecodes; ", bc_executed);
1750 }
1751 name()->print_value_on(&log);
1752 log.print_cr(" by thread " PTR_FORMAT " \"%s\" (" PTR_FORMAT ")",
1753 p2i(THREAD), THREAD->name(), p2i(this));
1754 }
1755 }
1756 LogTarget(Info, class, init) lt;
1757 if (lt.is_enabled()) {
1758 ResourceMark rm(THREAD);
1759 LogStream ls(lt);
1760 ls.print("%d Initialized ", init_id);
1761 name()->print_value_on(&ls);
1762 ls.print_cr("%s (" PTR_FORMAT ")", h_method() == nullptr ? "(no method)" : "", p2i(this));
1763 }
1764 }
1765
1766 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1767 InterpreterOopMap* entry_for) {
1768 // Lazily create the _oop_map_cache at first request.
1769 // Load_acquire is needed to safely get instance published with CAS by another thread.
1770 OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache);
1771 if (oop_map_cache == nullptr) {
1772 // Try to install new instance atomically.
1773 oop_map_cache = new OopMapCache();
1774 OopMapCache* other = Atomic::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
1775 if (other != nullptr) {
1776 // Someone else managed to install before us, ditch local copy and use the existing one.
1777 delete oop_map_cache;
1778 oop_map_cache = other;
1779 }
1780 }
1781 // _oop_map_cache is constant after init; lookup below does its own locking.
1782 oop_map_cache->lookup(method, bci, entry_for);
1783 }
1784
1785 bool InstanceKlass::contains_field_offset(int offset) {
2506 }
2507 }
2508 if (new_jmeths != 0) {
2509 Method::ensure_jmethod_ids(class_loader_data(), new_jmeths);
2510 }
2511 }
2512
2513 // Lookup a jmethodID, null if not found. Do no blocking, no allocations, no handles
2514 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
2515 int idnum = method->method_idnum();
2516 jmethodID* jmeths = methods_jmethod_ids_acquire();
2517 return (jmeths != nullptr) ? jmeths[idnum + 1] : nullptr;
2518 }
2519
2520 inline DependencyContext InstanceKlass::dependencies() {
2521 DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);
2522 return dep_context;
2523 }
2524
2525 void InstanceKlass::mark_dependent_nmethods(DeoptimizationScope* deopt_scope, KlassDepChange& changes) {
2526 dependencies().mark_dependent_nmethods(deopt_scope, changes, this);
2527 }
2528
2529 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2530 dependencies().add_dependent_nmethod(nm);
2531 }
2532
2533 void InstanceKlass::clean_dependency_context() {
2534 dependencies().clean_unloading_dependents();
2535 }
2536
2537 #ifndef PRODUCT
2538 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2539 dependencies().print_dependent_nmethods(verbose);
2540 }
2541
2542 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2543 return dependencies().is_dependent_nmethod(nm);
2544 }
2545 #endif //PRODUCT
2546
2635 if (itable_length() > 0) {
2636 itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2637 int method_table_offset_in_words = ioe->offset()/wordSize;
2638 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2639
2640 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2641 / itableOffsetEntry::size();
2642
2643 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2644 if (ioe->interface_klass() != nullptr) {
2645 it->push(ioe->interface_klass_addr());
2646 itableMethodEntry* ime = ioe->first_method_entry(this);
2647 int n = klassItable::method_count_for_interface(ioe->interface_klass());
2648 for (int index = 0; index < n; index ++) {
2649 it->push(ime[index].method_addr());
2650 }
2651 }
2652 }
2653 }
2654
2655 it->push(&_nest_host);
2656 it->push(&_nest_members);
2657 it->push(&_permitted_subclasses);
2658 it->push(&_record_components);
2659 }
2660
2661 #if INCLUDE_CDS
2662 void InstanceKlass::remove_unshareable_info() {
2663 if (is_linked()) {
2664 assert(can_be_verified_at_dumptime(), "must be");
2665 // Remember this so we can avoid walking the hierarchy at runtime.
2666 set_verified_at_dump_time();
2667 }
2668 _misc_flags.set_has_init_deps_processed(false);
2669
2670 Klass::remove_unshareable_info();
2671
2672 if (SystemDictionaryShared::has_class_failed_verification(this)) {
2673 // Classes are attempted to link during dumping and may fail,
2674 // but these classes are still in the dictionary and class list in CLD.
2675 // If the class has failed verification, there is nothing else to remove.
2676 return;
2677 }
2678
2679 // Reset to the 'allocated' state to prevent any premature accessing to
2680 // a shared class at runtime while the class is still being loaded and
2681 // restored. A class' init_state is set to 'loaded' at runtime when it's
2682 // being added to class hierarchy (see InstanceKlass:::add_to_hierarchy()).
2683 _init_state = allocated;
2684
2685 { // Otherwise this needs to take out the Compile_lock.
2686 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2687 init_implementor();
2688 }
2699 // do array classes also.
2700 if (array_klasses() != nullptr) {
2701 array_klasses()->remove_unshareable_info();
2702 }
2703
2704 // These are not allocated from metaspace. They are safe to set to null.
2705 _source_debug_extension = nullptr;
2706 _dep_context = nullptr;
2707 _osr_nmethods_head = nullptr;
2708 #if INCLUDE_JVMTI
2709 _breakpoints = nullptr;
2710 _previous_versions = nullptr;
2711 _cached_class_file = nullptr;
2712 _jvmti_cached_class_field_map = nullptr;
2713 #endif
2714
2715 _init_thread = nullptr;
2716 _methods_jmethod_ids = nullptr;
2717 _jni_ids = nullptr;
2718 _oop_map_cache = nullptr;
2719 if (CDSConfig::is_dumping_invokedynamic() && HeapShared::is_lambda_proxy_klass(this)) {
2720 // keep _nest_host
2721 } else {
2722 // clear _nest_host to ensure re-load at runtime
2723 _nest_host = nullptr;
2724 }
2725 init_shared_package_entry();
2726 _dep_context_last_cleaned = 0;
2727 DEBUG_ONLY(_shared_class_load_count = 0);
2728
2729 remove_unshareable_flags();
2730 }
2731
2732 void InstanceKlass::remove_unshareable_flags() {
2733 // clear all the flags/stats that shouldn't be in the archived version
2734 assert(!is_scratch_class(), "must be");
2735 assert(!has_been_redefined(), "must be");
2736 #if INCLUDE_JVMTI
2737 set_is_being_redefined(false);
2738 #endif
2739 set_has_resolved_methods(false);
2740 }
2741
2742 void InstanceKlass::remove_java_mirror() {
2743 Klass::remove_java_mirror();
2744
2745 // do array classes also.
2746 if (array_klasses() != nullptr) {
2747 array_klasses()->remove_java_mirror();
2813
2814 // restore constant pool resolved references
2815 constants()->restore_unshareable_info(CHECK);
2816
2817 if (array_klasses() != nullptr) {
2818 // To get a consistent list of classes we need MultiArray_lock to ensure
2819 // array classes aren't observed while they are being restored.
2820 RecursiveLocker rl(MultiArray_lock, THREAD);
2821 assert(this == array_klasses()->bottom_klass(), "sanity");
2822 // Array classes have null protection domain.
2823 // --> see ArrayKlass::complete_create_array_klass()
2824 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
2825 }
2826
2827 // Initialize @ValueBased class annotation if not already set in the archived klass.
2828 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
2829 set_is_value_based();
2830 }
2831 }
2832
2833 bool InstanceKlass::can_be_verified_at_dumptime() const {
2834 if (CDSConfig::preserve_all_dumptime_verification_states(this)) {
2835 return true;
2836 }
2837
2838 if (MetaspaceShared::is_in_shared_metaspace(this)) {
2839 // This is a class that was dumped into the base archive, so we know
2840 // it was verified at dump time.
2841 return true;
2842 }
2843
2844 if (CDSConfig::is_dumping_invokedynamic()) {
2845 // FIXME: this works around JDK-8315719
2846 return true;
2847 }
2848
2849 // Check if a class or any of its supertypes has a version older than 50.
2850 // CDS will not perform verification of old classes during dump time because
2851 // without changing the old verifier, the verification constraint cannot be
2852 // retrieved during dump time.
2853 // Verification of archived old classes will be performed during run time.
2854 if (major_version() < 50 /*JAVA_6_VERSION*/) {
2855 return false;
2856 }
2857 if (java_super() != nullptr && !java_super()->can_be_verified_at_dumptime()) {
2858 return false;
2859 }
2860 Array<InstanceKlass*>* interfaces = local_interfaces();
2861 int len = interfaces->length();
2862 for (int i = 0; i < len; i++) {
2863 if (!interfaces->at(i)->can_be_verified_at_dumptime()) {
2864 return false;
2865 }
2866 }
2867 return true;
2868 }
2869
2870 bool InstanceKlass::methods_contain_jsr_bytecode() const {
2871 Thread* thread = Thread::current();
2872 for (int i = 0; i < _methods->length(); i++) {
2873 methodHandle m(thread, _methods->at(i));
2874 BytecodeStream bcs(m);
2875 while (!bcs.is_last_bytecode()) {
2876 Bytecodes::Code opcode = bcs.next();
2877 if (opcode == Bytecodes::_jsr || opcode == Bytecodes::_jsr_w) {
2878 return true;
2879 }
2880 }
2881 }
2882 return false;
2883 }
2884
2885 int InstanceKlass::shared_class_loader_type() const {
2886 if (is_shared_boot_class()) {
2887 return ClassLoader::BOOT_LOADER;
2888 } else if (is_shared_platform_class()) {
2889 return ClassLoader::PLATFORM_LOADER;
2890 } else if (is_shared_app_class()) {
2891 return ClassLoader::APP_LOADER;
2892 } else {
2893 return ClassLoader::OTHER;
2894 }
2895 }
2896 #endif // INCLUDE_CDS
2897
2898 #if INCLUDE_JVMTI
2899 static void clear_all_breakpoints(Method* m) {
2900 m->clear_all_breakpoints();
2901 }
2902 #endif
2903
2904 void InstanceKlass::unload_class(InstanceKlass* ik) {
2905
2906 if (ik->is_scratch_class()) {
2907 assert(ik->dependencies().is_empty(), "dependencies should be empty for scratch classes");
2908 return;
2909 }
2910 assert(ik->is_loaded(), "class should be loaded " PTR_FORMAT, p2i(ik));
2911
2912 // Release dependencies.
2913 ik->dependencies().remove_all_dependents();
2914
2915 // notify the debugger
3649 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3650 for (int i = 0; i < len; i++) {
3651 intptr_t e = start[i];
3652 st->print("%d : " INTPTR_FORMAT, i, e);
3653 if (MetaspaceObj::is_valid((Metadata*)e)) {
3654 st->print(" ");
3655 ((Metadata*)e)->print_value_on(st);
3656 }
3657 st->cr();
3658 }
3659 }
3660
3661 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3662 return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3663 }
3664
3665 const char* InstanceKlass::init_state_name() const {
3666 return state_names[init_state()];
3667 }
3668
3669 const char* InstanceKlass::state2name(ClassState s) {
3670 return state_names[s];
3671 }
3672
3673 void InstanceKlass::print_on(outputStream* st) const {
3674 assert(is_klass(), "must be klass");
3675 Klass::print_on(st);
3676
3677 st->print(BULLET"instance size: %d", size_helper()); st->cr();
3678 st->print(BULLET"klass size: %d", size()); st->cr();
3679 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
3680 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
3681 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
3682 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
3683 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3684 st->print(BULLET"sub: ");
3685 Klass* sub = subklass();
3686 int n;
3687 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3688 if (n < MaxSubklassPrintSize) {
3689 sub->print_value_on(st);
3690 st->print(" ");
3691 }
3692 }
3982 nullptr;
3983 // caller can be null, for example, during a JVMTI VM_Init hook
3984 if (caller != nullptr) {
3985 info_stream.print(" source: instance of %s", caller->external_name());
3986 } else {
3987 // source is unknown
3988 }
3989 } else {
3990 oop class_loader = loader_data->class_loader();
3991 info_stream.print(" source: %s", class_loader->klass()->external_name());
3992 }
3993 } else {
3994 assert(this->is_shared(), "must be");
3995 if (MetaspaceShared::is_shared_dynamic((void*)this)) {
3996 info_stream.print(" source: shared objects file (top)");
3997 } else {
3998 info_stream.print(" source: shared objects file");
3999 }
4000 }
4001
4002 info_stream.print(" loader:");
4003 if (is_shared()) {
4004 info_stream.print(" %s", SystemDictionaryShared::class_loader_name_for_shared((Klass*)this));
4005 } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) {
4006 info_stream.print(" boot_loader");
4007 } else {
4008 oop class_loader = loader_data->class_loader();
4009 if (class_loader != nullptr) {
4010 info_stream.print(" %s", class_loader->klass()->external_name());
4011 oop cl_name_and_id = java_lang_ClassLoader::nameAndId(class_loader);
4012 if (cl_name_and_id != nullptr) {
4013 info_stream.print(" %s", java_lang_String::as_utf8_string(cl_name_and_id));
4014 }
4015 } else {
4016 info_stream.print(" null");
4017 }
4018 }
4019 msg.info("%s", info_stream.as_string());
4020
4021 if (log_is_enabled(Debug, class, load)) {
4022 stringStream debug_stream;
4023
4024 // Class hierarchy info
4025 debug_stream.print(" klass: " PTR_FORMAT " super: " PTR_FORMAT,
4026 p2i(this), p2i(superklass()));
4027
4028 // Interfaces
4029 if (local_interfaces() != nullptr && local_interfaces()->length() > 0) {
4030 debug_stream.print(" interfaces:");
4031 int length = local_interfaces()->length();
4032 for (int i = 0; i < length; i++) {
4033 debug_stream.print(" " PTR_FORMAT,
4034 p2i(InstanceKlass::cast(local_interfaces()->at(i))));
4035 }
4036 }
4037
4038 // Class loader
|