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"
762 OrderAccess::storestore();
763 java_lang_Class::clear_init_lock(java_mirror());
764 assert(!is_not_initialized(), "class must be initialized now");
765 }
766
767
768 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
769 // process. The step comments refers to the procedure described in that section.
770 // Note: implementation moved to static method to expose the this pointer.
771 void InstanceKlass::initialize(TRAPS) {
772 if (this->should_be_initialized()) {
773 initialize_impl(CHECK);
774 // Note: at this point the class may be initialized
775 // OR it may be in the state of being initialized
776 // in case of recursive initialization!
777 } else {
778 assert(is_initialized(), "sanity check");
779 }
780 }
781
782
783 bool InstanceKlass::verify_code(TRAPS) {
784 // 1) Verify the bytecodes
785 return Verifier::verify(this, should_verify_class(), THREAD);
786 }
787
788 void InstanceKlass::link_class(TRAPS) {
789 assert(is_loaded(), "must be loaded");
790 if (!is_linked()) {
791 link_class_impl(CHECK);
792 }
793 }
794
795 // Called to verify that a class can link during initialization, without
796 // throwing a VerifyError.
797 bool InstanceKlass::link_class_or_fail(TRAPS) {
798 assert(is_loaded(), "must be loaded");
799 if (!is_linked()) {
800 link_class_impl(CHECK_false);
801 }
953 return true;
954 }
955
956 // Rewrite the byte codes of all of the methods of a class.
957 // The rewriter must be called exactly once. Rewriting must happen after
958 // verification but before the first method of the class is executed.
959 void InstanceKlass::rewrite_class(TRAPS) {
960 assert(is_loaded(), "must be loaded");
961 if (is_rewritten()) {
962 assert(is_shared(), "rewriting an unshared class?");
963 return;
964 }
965 Rewriter::rewrite(this, CHECK);
966 set_rewritten();
967 }
968
969 // Now relocate and link method entry points after class is rewritten.
970 // This is outside is_rewritten flag. In case of an exception, it can be
971 // executed more than once.
972 void InstanceKlass::link_methods(TRAPS) {
973 PerfTraceTime timer(ClassLoader::perf_ik_link_methods_time());
974
975 int len = methods()->length();
976 for (int i = len-1; i >= 0; i--) {
977 methodHandle m(THREAD, methods()->at(i));
978
979 // Set up method entry points for compiler and interpreter .
980 m->link_method(m, CHECK);
981 }
982 }
983
984 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
985 void InstanceKlass::initialize_super_interfaces(TRAPS) {
986 assert (has_nonstatic_concrete_methods(), "caller should have checked this");
987 for (int i = 0; i < local_interfaces()->length(); ++i) {
988 InstanceKlass* ik = local_interfaces()->at(i);
989
990 // Initialization is depth first search ie. we start with top of the inheritance tree
991 // has_nonstatic_concrete_methods drives searching superinterfaces since it
992 // means has_nonstatic_concrete_methods in its superinterface hierarchy
993 if (ik->has_nonstatic_concrete_methods()) {
1062 assert_locked_or_safepoint(ClassInitError_lock);
1063 InitErrorTableCleaner cleaner;
1064 if (_initialization_error_table != nullptr) {
1065 _initialization_error_table->unlink(&cleaner);
1066 }
1067 }
1068
1069 void InstanceKlass::initialize_impl(TRAPS) {
1070 HandleMark hm(THREAD);
1071
1072 // Make sure klass is linked (verified) before initialization
1073 // A class could already be verified, since it has been reflected upon.
1074 link_class(CHECK);
1075
1076 DTRACE_CLASSINIT_PROBE(required, -1);
1077
1078 bool wait = false;
1079
1080 JavaThread* jt = THREAD;
1081
1082 bool debug_logging_enabled = log_is_enabled(Debug, class, init);
1083
1084 // refer to the JVM book page 47 for description of steps
1085 // Step 1
1086 {
1087 Handle h_init_lock(THREAD, init_lock());
1088 ObjectLocker ol(h_init_lock, jt);
1089
1090 // Step 2
1091 // If we were to use wait() instead of waitInterruptibly() then
1092 // we might end up throwing IE from link/symbol resolution sites
1093 // that aren't expected to throw. This would wreak havoc. See 6320309.
1094 while (is_being_initialized() && !is_reentrant_initialization(jt)) {
1095 if (debug_logging_enabled) {
1096 ResourceMark rm(jt);
1097 log_debug(class, init)("Thread \"%s\" waiting for initialization of %s by thread \"%s\"",
1098 jt->name(), external_name(), init_thread_name());
1099 }
1100 wait = true;
1101 jt->set_class_to_be_initialized(this);
1200 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1201 ClassLoader::perf_class_init_selftime(),
1202 ClassLoader::perf_classes_inited(),
1203 jt->get_thread_stat()->perf_recursion_counts_addr(),
1204 jt->get_thread_stat()->perf_timers_addr(),
1205 PerfClassTraceTime::CLASS_CLINIT);
1206 call_class_initializer(THREAD);
1207 } else {
1208 // The elapsed time is so small it's not worth counting.
1209 if (UsePerfData) {
1210 ClassLoader::perf_classes_inited()->inc();
1211 }
1212 call_class_initializer(THREAD);
1213 }
1214 }
1215
1216 // Step 9
1217 if (!HAS_PENDING_EXCEPTION) {
1218 set_initialization_state_and_notify(fully_initialized, CHECK);
1219 debug_only(vtable().verify(tty, true);)
1220 }
1221 else {
1222 // Step 10 and 11
1223 Handle e(THREAD, PENDING_EXCEPTION);
1224 CLEAR_PENDING_EXCEPTION;
1225 // JVMTI has already reported the pending exception
1226 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1227 JvmtiExport::clear_detected_exception(jt);
1228 {
1229 EXCEPTION_MARK;
1230 add_initialization_error(THREAD, e);
1231 set_initialization_state_and_notify(initialization_error, THREAD);
1232 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1233 // JVMTI has already reported the pending exception
1234 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1235 JvmtiExport::clear_detected_exception(jt);
1236 }
1237 DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1238 if (e->is_a(vmClasses::Error_klass())) {
1239 THROW_OOP(e());
1240 } else {
1241 JavaCallArguments args(e);
1242 THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
1243 vmSymbols::throwable_void_signature(),
1244 &args);
1245 }
1246 }
1247 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1248 }
1249
1250
1251 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1252 Handle h_init_lock(THREAD, init_lock());
1253 if (h_init_lock() != nullptr) {
1254 ObjectLocker ol(h_init_lock, THREAD);
1255 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1256 set_init_state(state);
1257 fence_and_clear_init_lock();
1258 ol.notify_all(CHECK);
1259 } else {
1260 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1261 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1262 set_init_state(state);
1263 }
1264 }
1265
1266 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1267 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1268 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1269 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1270
1469 tty->print("Registered ");
1470 i->print_value_on(tty);
1471 tty->print_cr(" (" PTR_FORMAT ") as finalizable", p2i(i));
1472 }
1473 instanceHandle h_i(THREAD, i);
1474 // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1475 JavaValue result(T_VOID);
1476 JavaCallArguments args(h_i);
1477 methodHandle mh(THREAD, Universe::finalizer_register_method());
1478 JavaCalls::call(&result, mh, &args, CHECK_NULL);
1479 MANAGEMENT_ONLY(FinalizerService::on_register(h_i(), THREAD);)
1480 return h_i();
1481 }
1482
1483 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1484 assert(!is_abstract() && !is_interface(), "Should not create this object");
1485 size_t size = size_helper(); // Query before forming handle.
1486 return (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);
1487 }
1488
1489 instanceOop InstanceKlass::allocate_instance(oop java_class, TRAPS) {
1490 Klass* k = java_lang_Class::as_Klass(java_class);
1491 if (k == nullptr) {
1492 ResourceMark rm(THREAD);
1493 THROW_(vmSymbols::java_lang_InstantiationException(), nullptr);
1494 }
1495 InstanceKlass* ik = cast(k);
1496 ik->check_valid_for_instantiation(false, CHECK_NULL);
1497 ik->initialize(CHECK_NULL);
1498 return ik->allocate_instance(THREAD);
1499 }
1500
1501 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1502 return instanceHandle(THREAD, allocate_instance(THREAD));
1503 }
1504
1505 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1506 if (is_interface() || is_abstract()) {
1507 ResourceMark rm(THREAD);
1508 THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1509 : vmSymbols::java_lang_InstantiationException(), external_name());
1537 }
1538
1539 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1540 // Need load-acquire for lock-free read
1541 ObjArrayKlass* oak = array_klasses_acquire();
1542 if (oak == nullptr) {
1543 return nullptr;
1544 } else {
1545 return oak->array_klass_or_null(n);
1546 }
1547 }
1548
1549 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1550 return array_klass(1, THREAD);
1551 }
1552
1553 ArrayKlass* InstanceKlass::array_klass_or_null() {
1554 return array_klass_or_null(1);
1555 }
1556
1557 static int call_class_initializer_counter = 0; // for debugging
1558
1559 Method* InstanceKlass::class_initializer() const {
1560 Method* clinit = find_method(
1561 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1562 if (clinit != nullptr && clinit->has_valid_initializer_flags()) {
1563 return clinit;
1564 }
1565 return nullptr;
1566 }
1567
1568 void InstanceKlass::call_class_initializer(TRAPS) {
1569 if (ReplayCompiles &&
1570 (ReplaySuppressInitializers == 1 ||
1571 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1572 // Hide the existence of the initializer for the purpose of replaying the compile
1573 return;
1574 }
1575
1576 #if INCLUDE_CDS
1577 // This is needed to ensure the consistency of the archived heap objects.
1578 if (has_archived_enum_objs()) {
1579 assert(is_shared(), "must be");
1580 bool initialized = CDSEnumKlass::initialize_enum_klass(this, CHECK);
1581 if (initialized) {
1582 return;
1583 }
1584 }
1585 #endif
1586
1587 methodHandle h_method(THREAD, class_initializer());
1588 assert(!is_initialized(), "we cannot initialize twice");
1589 LogTarget(Info, class, init) lt;
1590 if (lt.is_enabled()) {
1591 ResourceMark rm(THREAD);
1592 LogStream ls(lt);
1593 ls.print("%d Initializing ", call_class_initializer_counter++);
1594 name()->print_value_on(&ls);
1595 ls.print_cr("%s (" PTR_FORMAT ") by thread \"%s\"",
1596 h_method() == nullptr ? "(no method)" : "", p2i(this),
1597 THREAD->name());
1598 }
1599 if (h_method() != nullptr) {
1600 JavaCallArguments args; // No arguments
1601 JavaValue result(T_VOID);
1602 JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1603 }
1604 }
1605
1606
1607 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1608 InterpreterOopMap* entry_for) {
1609 // Lazily create the _oop_map_cache at first request.
1610 // Load_acquire is needed to safely get instance published with CAS by another thread.
1611 OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache);
1612 if (oop_map_cache == nullptr) {
1613 // Try to install new instance atomically.
1614 oop_map_cache = new OopMapCache();
1615 OopMapCache* other = Atomic::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
1616 if (other != nullptr) {
1617 // Someone else managed to install before us, ditch local copy and use the existing one.
1618 delete oop_map_cache;
1619 oop_map_cache = other;
1620 }
1621 }
1622 // _oop_map_cache is constant after init; lookup below does its own locking.
1623 oop_map_cache->lookup(method, bci, entry_for);
1624 }
1625
1626 bool InstanceKlass::contains_field_offset(int offset) {
2347 }
2348 }
2349 if (new_jmeths != 0) {
2350 Method::ensure_jmethod_ids(class_loader_data(), new_jmeths);
2351 }
2352 }
2353
2354 // Lookup a jmethodID, null if not found. Do no blocking, no allocations, no handles
2355 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
2356 int idnum = method->method_idnum();
2357 jmethodID* jmeths = methods_jmethod_ids_acquire();
2358 return (jmeths != nullptr) ? jmeths[idnum + 1] : nullptr;
2359 }
2360
2361 inline DependencyContext InstanceKlass::dependencies() {
2362 DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);
2363 return dep_context;
2364 }
2365
2366 void InstanceKlass::mark_dependent_nmethods(DeoptimizationScope* deopt_scope, KlassDepChange& changes) {
2367 dependencies().mark_dependent_nmethods(deopt_scope, changes);
2368 }
2369
2370 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2371 dependencies().add_dependent_nmethod(nm);
2372 }
2373
2374 void InstanceKlass::clean_dependency_context() {
2375 dependencies().clean_unloading_dependents();
2376 }
2377
2378 #ifndef PRODUCT
2379 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2380 dependencies().print_dependent_nmethods(verbose);
2381 }
2382
2383 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2384 return dependencies().is_dependent_nmethod(nm);
2385 }
2386 #endif //PRODUCT
2387
2476 if (itable_length() > 0) {
2477 itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2478 int method_table_offset_in_words = ioe->offset()/wordSize;
2479 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2480
2481 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2482 / itableOffsetEntry::size();
2483
2484 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2485 if (ioe->interface_klass() != nullptr) {
2486 it->push(ioe->interface_klass_addr());
2487 itableMethodEntry* ime = ioe->first_method_entry(this);
2488 int n = klassItable::method_count_for_interface(ioe->interface_klass());
2489 for (int index = 0; index < n; index ++) {
2490 it->push(ime[index].method_addr());
2491 }
2492 }
2493 }
2494 }
2495
2496 it->push(&_nest_members);
2497 it->push(&_permitted_subclasses);
2498 it->push(&_record_components);
2499 }
2500
2501 #if INCLUDE_CDS
2502 void InstanceKlass::remove_unshareable_info() {
2503
2504 if (is_linked()) {
2505 assert(can_be_verified_at_dumptime(), "must be");
2506 // Remember this so we can avoid walking the hierarchy at runtime.
2507 set_verified_at_dump_time();
2508 }
2509
2510 Klass::remove_unshareable_info();
2511
2512 if (SystemDictionaryShared::has_class_failed_verification(this)) {
2513 // Classes are attempted to link during dumping and may fail,
2514 // but these classes are still in the dictionary and class list in CLD.
2515 // If the class has failed verification, there is nothing else to remove.
2516 return;
2517 }
2518
2519 // Reset to the 'allocated' state to prevent any premature accessing to
2520 // a shared class at runtime while the class is still being loaded and
2521 // restored. A class' init_state is set to 'loaded' at runtime when it's
2522 // being added to class hierarchy (see InstanceKlass:::add_to_hierarchy()).
2523 _init_state = allocated;
2524
2525 { // Otherwise this needs to take out the Compile_lock.
2526 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2527 init_implementor();
2528 }
2539 // do array classes also.
2540 if (array_klasses() != nullptr) {
2541 array_klasses()->remove_unshareable_info();
2542 }
2543
2544 // These are not allocated from metaspace. They are safe to set to null.
2545 _source_debug_extension = nullptr;
2546 _dep_context = nullptr;
2547 _osr_nmethods_head = nullptr;
2548 #if INCLUDE_JVMTI
2549 _breakpoints = nullptr;
2550 _previous_versions = nullptr;
2551 _cached_class_file = nullptr;
2552 _jvmti_cached_class_field_map = nullptr;
2553 #endif
2554
2555 _init_thread = nullptr;
2556 _methods_jmethod_ids = nullptr;
2557 _jni_ids = nullptr;
2558 _oop_map_cache = nullptr;
2559 // clear _nest_host to ensure re-load at runtime
2560 _nest_host = nullptr;
2561 init_shared_package_entry();
2562 _dep_context_last_cleaned = 0;
2563
2564 remove_unshareable_flags();
2565 }
2566
2567 void InstanceKlass::remove_unshareable_flags() {
2568 // clear all the flags/stats that shouldn't be in the archived version
2569 assert(!is_scratch_class(), "must be");
2570 assert(!has_been_redefined(), "must be");
2571 #if INCLUDE_JVMTI
2572 set_is_being_redefined(false);
2573 #endif
2574 set_has_resolved_methods(false);
2575 }
2576
2577 void InstanceKlass::remove_java_mirror() {
2578 Klass::remove_java_mirror();
2579
2580 // do array classes also.
2581 if (array_klasses() != nullptr) {
2582 array_klasses()->remove_java_mirror();
2648
2649 // restore constant pool resolved references
2650 constants()->restore_unshareable_info(CHECK);
2651
2652 if (array_klasses() != nullptr) {
2653 // To get a consistent list of classes we need MultiArray_lock to ensure
2654 // array classes aren't observed while they are being restored.
2655 RecursiveLocker rl(MultiArray_lock, THREAD);
2656 assert(this == array_klasses()->bottom_klass(), "sanity");
2657 // Array classes have null protection domain.
2658 // --> see ArrayKlass::complete_create_array_klass()
2659 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
2660 }
2661
2662 // Initialize @ValueBased class annotation
2663 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation()) {
2664 set_is_value_based();
2665 }
2666 }
2667
2668 // Check if a class or any of its supertypes has a version older than 50.
2669 // CDS will not perform verification of old classes during dump time because
2670 // without changing the old verifier, the verification constraint cannot be
2671 // retrieved during dump time.
2672 // Verification of archived old classes will be performed during run time.
2673 bool InstanceKlass::can_be_verified_at_dumptime() const {
2674 if (MetaspaceShared::is_in_shared_metaspace(this)) {
2675 // This is a class that was dumped into the base archive, so we know
2676 // it was verified at dump time.
2677 return true;
2678 }
2679 if (major_version() < 50 /*JAVA_6_VERSION*/) {
2680 return false;
2681 }
2682 if (java_super() != nullptr && !java_super()->can_be_verified_at_dumptime()) {
2683 return false;
2684 }
2685 Array<InstanceKlass*>* interfaces = local_interfaces();
2686 int len = interfaces->length();
2687 for (int i = 0; i < len; i++) {
2688 if (!interfaces->at(i)->can_be_verified_at_dumptime()) {
2689 return false;
2690 }
2691 }
2692 return true;
2693 }
2694
2695 bool InstanceKlass::methods_contain_jsr_bytecode() const {
2696 Thread* thread = Thread::current();
2697 for (int i = 0; i < _methods->length(); i++) {
2698 methodHandle m(thread, _methods->at(i));
2699 BytecodeStream bcs(m);
2700 while (!bcs.is_last_bytecode()) {
2701 Bytecodes::Code opcode = bcs.next();
2702 if (opcode == Bytecodes::_jsr || opcode == Bytecodes::_jsr_w) {
2703 return true;
2704 }
2705 }
2706 }
2707 return false;
2708 }
2709 #endif // INCLUDE_CDS
2710
2711 #if INCLUDE_JVMTI
2712 static void clear_all_breakpoints(Method* m) {
2713 m->clear_all_breakpoints();
2714 }
2715 #endif
2716
2717 void InstanceKlass::unload_class(InstanceKlass* ik) {
2718 // Release dependencies.
2719 ik->dependencies().remove_all_dependents();
2720
2721 // notify the debugger
2722 if (JvmtiExport::should_post_class_unload()) {
2723 JvmtiExport::post_class_unload(ik);
2724 }
2725
2726 // notify ClassLoadingService of class unload
2727 ClassLoadingService::notify_class_unloaded(ik);
2728
3455 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3456 for (int i = 0; i < len; i++) {
3457 intptr_t e = start[i];
3458 st->print("%d : " INTPTR_FORMAT, i, e);
3459 if (MetaspaceObj::is_valid((Metadata*)e)) {
3460 st->print(" ");
3461 ((Metadata*)e)->print_value_on(st);
3462 }
3463 st->cr();
3464 }
3465 }
3466
3467 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3468 return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3469 }
3470
3471 const char* InstanceKlass::init_state_name() const {
3472 return state_names[init_state()];
3473 }
3474
3475 void InstanceKlass::print_on(outputStream* st) const {
3476 assert(is_klass(), "must be klass");
3477 Klass::print_on(st);
3478
3479 st->print(BULLET"instance size: %d", size_helper()); st->cr();
3480 st->print(BULLET"klass size: %d", size()); st->cr();
3481 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
3482 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
3483 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
3484 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
3485 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3486 st->print(BULLET"sub: ");
3487 Klass* sub = subklass();
3488 int n;
3489 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3490 if (n < MaxSubklassPrintSize) {
3491 sub->print_value_on(st);
3492 st->print(" ");
3493 }
3494 }
3784 nullptr;
3785 // caller can be null, for example, during a JVMTI VM_Init hook
3786 if (caller != nullptr) {
3787 info_stream.print(" source: instance of %s", caller->external_name());
3788 } else {
3789 // source is unknown
3790 }
3791 } else {
3792 oop class_loader = loader_data->class_loader();
3793 info_stream.print(" source: %s", class_loader->klass()->external_name());
3794 }
3795 } else {
3796 assert(this->is_shared(), "must be");
3797 if (MetaspaceShared::is_shared_dynamic((void*)this)) {
3798 info_stream.print(" source: shared objects file (top)");
3799 } else {
3800 info_stream.print(" source: shared objects file");
3801 }
3802 }
3803
3804 msg.info("%s", info_stream.as_string());
3805
3806 if (log_is_enabled(Debug, class, load)) {
3807 stringStream debug_stream;
3808
3809 // Class hierarchy info
3810 debug_stream.print(" klass: " PTR_FORMAT " super: " PTR_FORMAT,
3811 p2i(this), p2i(superklass()));
3812
3813 // Interfaces
3814 if (local_interfaces() != nullptr && local_interfaces()->length() > 0) {
3815 debug_stream.print(" interfaces:");
3816 int length = local_interfaces()->length();
3817 for (int i = 0; i < length; i++) {
3818 debug_stream.print(" " PTR_FORMAT,
3819 p2i(InstanceKlass::cast(local_interfaces()->at(i))));
3820 }
3821 }
3822
3823 // 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"
764 OrderAccess::storestore();
765 java_lang_Class::clear_init_lock(java_mirror());
766 assert(!is_not_initialized(), "class must be initialized now");
767 }
768
769
770 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
771 // process. The step comments refers to the procedure described in that section.
772 // Note: implementation moved to static method to expose the this pointer.
773 void InstanceKlass::initialize(TRAPS) {
774 if (this->should_be_initialized()) {
775 initialize_impl(CHECK);
776 // Note: at this point the class may be initialized
777 // OR it may be in the state of being initialized
778 // in case of recursive initialization!
779 } else {
780 assert(is_initialized(), "sanity check");
781 }
782 }
783
784 static bool are_super_types_initialized(InstanceKlass* ik) {
785 InstanceKlass* s = ik->java_super();
786 if (s != nullptr && !s->is_initialized()) {
787 return false;
788 }
789
790 if (ik->has_nonstatic_concrete_methods()) {
791 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
792 // having a superinterface that declares, non-static, concrete methods
793 Array<InstanceKlass*>* interfaces = ik->local_interfaces();
794 int len = interfaces->length();
795 for (int i = 0; i < len; i++) {
796 InstanceKlass* intf = interfaces->at(i);
797 if (!intf->is_initialized()) {
798 return false;
799 }
800 }
801 }
802
803 return true;
804 }
805
806 static void log_class_init_start(outputStream* st, JavaThread* current, InstanceKlass* ik, int init_id) {
807 ResourceMark rm;
808 const char* info = "";
809 if (ik->has_preinitialized_mirror() && CDSConfig::is_loading_heap()) {
810 info = " (preinitialized)";
811 } else if (ik->class_initializer() == nullptr) {
812 info = " (no method)";
813 }
814 st->print("%d Initializing ", init_id);
815 ik->name()->print_value_on(st);
816 st->print_cr("%s (" PTR_FORMAT ") by thread " PTR_FORMAT " \"%s\"", info, p2i(ik), p2i(current), current->name());
817 }
818
819 static int log_class_init(JavaThread* current, InstanceKlass* ik) {
820 int init_id = -1;
821 LogStreamHandle(Info, init, class) lsh1;
822 LogStreamHandle(Debug, init) lsh2;
823 if (lsh1.is_enabled() || lsh2.is_enabled()) {
824 static int call_class_initializer_counter = 0; // for debugging
825 init_id = Atomic::fetch_then_add(&call_class_initializer_counter, 1);
826 if (lsh1.is_enabled()) {
827 log_class_init_start(&lsh1, current, ik, init_id);
828 }
829 if (lsh2.is_enabled() && ik->class_initializer() != nullptr && !ik->has_preinitialized_mirror()) {
830 log_class_init_start(&lsh2, current, ik, init_id);
831 }
832 }
833 return init_id;
834 }
835
836 void InstanceKlass::initialize_from_cds(TRAPS) {
837 if (is_initialized()) {
838 return;
839 }
840
841 if (has_preinitialized_mirror() && CDSConfig::is_loading_heap() &&
842 !ForceProfiling &&
843 !RecordTraining &&
844 are_super_types_initialized(this)) {
845 // FIXME: also check for events listeners such as JVMTI, JFR, etc
846 if (log_is_enabled(Info, cds, init)) {
847 ResourceMark rm;
848 log_info(cds, init)("%s (quickest)", external_name());
849 }
850
851 link_class(CHECK);
852
853 #ifdef AZZERT
854 {
855 MonitorLocker ml(THREAD, _init_monitor);
856 assert(!initialized(), "sanity");
857 assert(!is_being_initialized(), "sanity");
858 assert(!is_in_error_state(), "sanity");
859 }
860 #endif
861
862 log_class_init(THREAD, this);
863 set_init_thread(THREAD);
864 set_initialization_state_and_notify(fully_initialized, CHECK);
865 return;
866 }
867
868 if (log_is_enabled(Info, cds, init)) {
869 ResourceMark rm;
870 log_info(cds, init)("%s%s", external_name(),
871 (has_preinitialized_mirror() && CDSConfig::is_loading_heap()) ? " (quicker)" : "");
872 }
873 initialize(THREAD);
874 }
875
876 bool InstanceKlass::verify_code(TRAPS) {
877 // 1) Verify the bytecodes
878 return Verifier::verify(this, should_verify_class(), THREAD);
879 }
880
881 void InstanceKlass::link_class(TRAPS) {
882 assert(is_loaded(), "must be loaded");
883 if (!is_linked()) {
884 link_class_impl(CHECK);
885 }
886 }
887
888 // Called to verify that a class can link during initialization, without
889 // throwing a VerifyError.
890 bool InstanceKlass::link_class_or_fail(TRAPS) {
891 assert(is_loaded(), "must be loaded");
892 if (!is_linked()) {
893 link_class_impl(CHECK_false);
894 }
1046 return true;
1047 }
1048
1049 // Rewrite the byte codes of all of the methods of a class.
1050 // The rewriter must be called exactly once. Rewriting must happen after
1051 // verification but before the first method of the class is executed.
1052 void InstanceKlass::rewrite_class(TRAPS) {
1053 assert(is_loaded(), "must be loaded");
1054 if (is_rewritten()) {
1055 assert(is_shared(), "rewriting an unshared class?");
1056 return;
1057 }
1058 Rewriter::rewrite(this, CHECK);
1059 set_rewritten();
1060 }
1061
1062 // Now relocate and link method entry points after class is rewritten.
1063 // This is outside is_rewritten flag. In case of an exception, it can be
1064 // executed more than once.
1065 void InstanceKlass::link_methods(TRAPS) {
1066 PerfTraceElapsedTime timer(ClassLoader::perf_ik_link_methods_time());
1067
1068 int len = methods()->length();
1069 for (int i = len-1; i >= 0; i--) {
1070 methodHandle m(THREAD, methods()->at(i));
1071
1072 // Set up method entry points for compiler and interpreter .
1073 m->link_method(m, CHECK);
1074 }
1075 }
1076
1077 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
1078 void InstanceKlass::initialize_super_interfaces(TRAPS) {
1079 assert (has_nonstatic_concrete_methods(), "caller should have checked this");
1080 for (int i = 0; i < local_interfaces()->length(); ++i) {
1081 InstanceKlass* ik = local_interfaces()->at(i);
1082
1083 // Initialization is depth first search ie. we start with top of the inheritance tree
1084 // has_nonstatic_concrete_methods drives searching superinterfaces since it
1085 // means has_nonstatic_concrete_methods in its superinterface hierarchy
1086 if (ik->has_nonstatic_concrete_methods()) {
1155 assert_locked_or_safepoint(ClassInitError_lock);
1156 InitErrorTableCleaner cleaner;
1157 if (_initialization_error_table != nullptr) {
1158 _initialization_error_table->unlink(&cleaner);
1159 }
1160 }
1161
1162 void InstanceKlass::initialize_impl(TRAPS) {
1163 HandleMark hm(THREAD);
1164
1165 // Make sure klass is linked (verified) before initialization
1166 // A class could already be verified, since it has been reflected upon.
1167 link_class(CHECK);
1168
1169 DTRACE_CLASSINIT_PROBE(required, -1);
1170
1171 bool wait = false;
1172
1173 JavaThread* jt = THREAD;
1174
1175 if (ForceProfiling) {
1176 // Preallocate MDOs.
1177 for (int i = 0; i < methods()->length(); i++) {
1178 assert(!HAS_PENDING_EXCEPTION, "");
1179 methodHandle m(THREAD, methods()->at(i));
1180 Method::build_profiling_method_data(m, THREAD);
1181 if (HAS_PENDING_EXCEPTION) {
1182 ResourceMark rm;
1183 log_warning(cds)("MDO preallocation failed for %s", external_name());
1184 CLEAR_PENDING_EXCEPTION;
1185 break;
1186 }
1187 }
1188 }
1189
1190 bool debug_logging_enabled = log_is_enabled(Debug, class, init);
1191
1192 // refer to the JVM book page 47 for description of steps
1193 // Step 1
1194 {
1195 Handle h_init_lock(THREAD, init_lock());
1196 ObjectLocker ol(h_init_lock, jt);
1197
1198 // Step 2
1199 // If we were to use wait() instead of waitInterruptibly() then
1200 // we might end up throwing IE from link/symbol resolution sites
1201 // that aren't expected to throw. This would wreak havoc. See 6320309.
1202 while (is_being_initialized() && !is_reentrant_initialization(jt)) {
1203 if (debug_logging_enabled) {
1204 ResourceMark rm(jt);
1205 log_debug(class, init)("Thread \"%s\" waiting for initialization of %s by thread \"%s\"",
1206 jt->name(), external_name(), init_thread_name());
1207 }
1208 wait = true;
1209 jt->set_class_to_be_initialized(this);
1308 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1309 ClassLoader::perf_class_init_selftime(),
1310 ClassLoader::perf_classes_inited(),
1311 jt->get_thread_stat()->perf_recursion_counts_addr(),
1312 jt->get_thread_stat()->perf_timers_addr(),
1313 PerfClassTraceTime::CLASS_CLINIT);
1314 call_class_initializer(THREAD);
1315 } else {
1316 // The elapsed time is so small it's not worth counting.
1317 if (UsePerfData) {
1318 ClassLoader::perf_classes_inited()->inc();
1319 }
1320 call_class_initializer(THREAD);
1321 }
1322 }
1323
1324 // Step 9
1325 if (!HAS_PENDING_EXCEPTION) {
1326 set_initialization_state_and_notify(fully_initialized, CHECK);
1327 debug_only(vtable().verify(tty, true);)
1328 CompilationPolicy::replay_training_at_init(this, THREAD);
1329 }
1330 else {
1331 // Step 10 and 11
1332 Handle e(THREAD, PENDING_EXCEPTION);
1333 CLEAR_PENDING_EXCEPTION;
1334 // JVMTI has already reported the pending exception
1335 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1336 JvmtiExport::clear_detected_exception(jt);
1337 {
1338 EXCEPTION_MARK;
1339 add_initialization_error(THREAD, e);
1340 set_initialization_state_and_notify(initialization_error, THREAD);
1341 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1342 // JVMTI has already reported the pending exception
1343 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1344 JvmtiExport::clear_detected_exception(jt);
1345 }
1346 DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1347 if (e->is_a(vmClasses::Error_klass())) {
1348 THROW_OOP(e());
1349 } else {
1350 JavaCallArguments args(e);
1351 THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
1352 vmSymbols::throwable_void_signature(),
1353 &args);
1354 }
1355 }
1356 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1357 }
1358
1359 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1360 Handle h_init_lock(THREAD, init_lock());
1361 if (h_init_lock() != nullptr) {
1362 ObjectLocker ol(h_init_lock, THREAD);
1363 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1364 set_init_state(state);
1365 fence_and_clear_init_lock();
1366 ol.notify_all(CHECK);
1367 } else {
1368 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1369 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1370 set_init_state(state);
1371 }
1372 }
1373
1374 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1375 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1376 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1377 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1378
1577 tty->print("Registered ");
1578 i->print_value_on(tty);
1579 tty->print_cr(" (" PTR_FORMAT ") as finalizable", p2i(i));
1580 }
1581 instanceHandle h_i(THREAD, i);
1582 // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1583 JavaValue result(T_VOID);
1584 JavaCallArguments args(h_i);
1585 methodHandle mh(THREAD, Universe::finalizer_register_method());
1586 JavaCalls::call(&result, mh, &args, CHECK_NULL);
1587 MANAGEMENT_ONLY(FinalizerService::on_register(h_i(), THREAD);)
1588 return h_i();
1589 }
1590
1591 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1592 assert(!is_abstract() && !is_interface(), "Should not create this object");
1593 size_t size = size_helper(); // Query before forming handle.
1594 return (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);
1595 }
1596
1597 instanceOop InstanceKlass::allocate_instance(oop java_class,
1598 const char* who,
1599 TRAPS) {
1600 Klass* k = java_lang_Class::as_Klass(java_class);
1601 if (k == nullptr) {
1602 ResourceMark rm(THREAD);
1603 THROW_(vmSymbols::java_lang_InstantiationException(), nullptr);
1604 }
1605 InstanceKlass* ik = cast(k);
1606 ik->check_valid_for_instantiation(false, CHECK_NULL);
1607 ik->initialize(CHECK_NULL);
1608 return ik->allocate_instance(THREAD);
1609 }
1610
1611 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1612 return instanceHandle(THREAD, allocate_instance(THREAD));
1613 }
1614
1615 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1616 if (is_interface() || is_abstract()) {
1617 ResourceMark rm(THREAD);
1618 THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1619 : vmSymbols::java_lang_InstantiationException(), external_name());
1647 }
1648
1649 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1650 // Need load-acquire for lock-free read
1651 ObjArrayKlass* oak = array_klasses_acquire();
1652 if (oak == nullptr) {
1653 return nullptr;
1654 } else {
1655 return oak->array_klass_or_null(n);
1656 }
1657 }
1658
1659 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1660 return array_klass(1, THREAD);
1661 }
1662
1663 ArrayKlass* InstanceKlass::array_klass_or_null() {
1664 return array_klass_or_null(1);
1665 }
1666
1667 Method* InstanceKlass::class_initializer() const {
1668 Method* clinit = find_method(
1669 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1670 if (clinit != nullptr && clinit->has_valid_initializer_flags()) {
1671 return clinit;
1672 }
1673 return nullptr;
1674 }
1675
1676 void InstanceKlass::call_class_initializer(TRAPS) {
1677 if (ReplayCompiles &&
1678 (ReplaySuppressInitializers == 1 ||
1679 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1680 // Hide the existence of the initializer for the purpose of replaying the compile
1681 return;
1682 }
1683
1684 #if INCLUDE_CDS
1685 // This is needed to ensure the consistency of the archived heap objects.
1686 if (has_archived_enum_objs()) {
1687 assert(is_shared(), "must be");
1688 bool initialized = CDSEnumKlass::initialize_enum_klass(this, CHECK);
1689 if (initialized) {
1690 return;
1691 }
1692 } else if (has_preinitialized_mirror() && CDSConfig::is_loading_heap()) {
1693 log_class_init(THREAD, this);
1694 return;
1695 }
1696 #endif
1697
1698 methodHandle h_method(THREAD, class_initializer());
1699 assert(!is_initialized(), "we cannot initialize twice");
1700 int init_id = log_class_init(THREAD, this);
1701 if (h_method() != nullptr) {
1702 JavaCallArguments args; // No arguments
1703 JavaValue result(T_VOID);
1704 InstanceKlass* outer = THREAD->set_class_being_initialized(this);
1705 jlong bc_start = (CountBytecodesPerThread ? THREAD->bc_counter_value() : BytecodeCounter::counter_value());
1706
1707 elapsedTimer timer;
1708 {
1709 PerfPauseTimer pt(THREAD->current_rt_call_timer(), THREAD->profile_rt_calls());
1710 PauseRuntimeCallProfiling prcp(THREAD, THREAD->profile_rt_calls());
1711
1712 timer.start();
1713 JavaCalls::call(&result, h_method, &args, THREAD); // Static call (no args)
1714 timer.stop();
1715 }
1716
1717 jlong bc_end = (CountBytecodesPerThread ? THREAD->bc_counter_value() : BytecodeCounter::counter_value());
1718
1719 jlong bc_executed = (bc_end - bc_start);
1720 if (UsePerfData && outer == nullptr) { // outermost clinit
1721 THREAD->inc_clinit_bc_counter_value(bc_executed);
1722 ClassLoader::perf_class_init_bytecodes_count()->inc(bc_executed);
1723 }
1724
1725 THREAD->set_class_being_initialized(outer);
1726
1727 LogStreamHandle(Debug, init) log;
1728 if (log.is_enabled()) {
1729 ResourceMark rm(THREAD);
1730 log.print("%d Initialized in %.3fms (total: %ldms); ",
1731 init_id, timer.seconds() * 1000.0, ClassLoader::class_init_time_ms());
1732 if (CountBytecodes || CountBytecodesPerThread) {
1733 log.print("executed %ld bytecodes; ", bc_executed);
1734 }
1735 name()->print_value_on(&log);
1736 log.print_cr(" by thread " PTR_FORMAT " \"%s\" (" PTR_FORMAT ")",
1737 p2i(THREAD), THREAD->name(), p2i(this));
1738 }
1739 }
1740 LogTarget(Info, class, init) lt;
1741 if (lt.is_enabled()) {
1742 ResourceMark rm(THREAD);
1743 LogStream ls(lt);
1744 ls.print("%d Initialized ", init_id);
1745 name()->print_value_on(&ls);
1746 ls.print_cr("%s (" PTR_FORMAT ")", h_method() == nullptr ? "(no method)" : "", p2i(this));
1747 }
1748 }
1749
1750 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1751 InterpreterOopMap* entry_for) {
1752 // Lazily create the _oop_map_cache at first request.
1753 // Load_acquire is needed to safely get instance published with CAS by another thread.
1754 OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache);
1755 if (oop_map_cache == nullptr) {
1756 // Try to install new instance atomically.
1757 oop_map_cache = new OopMapCache();
1758 OopMapCache* other = Atomic::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
1759 if (other != nullptr) {
1760 // Someone else managed to install before us, ditch local copy and use the existing one.
1761 delete oop_map_cache;
1762 oop_map_cache = other;
1763 }
1764 }
1765 // _oop_map_cache is constant after init; lookup below does its own locking.
1766 oop_map_cache->lookup(method, bci, entry_for);
1767 }
1768
1769 bool InstanceKlass::contains_field_offset(int offset) {
2490 }
2491 }
2492 if (new_jmeths != 0) {
2493 Method::ensure_jmethod_ids(class_loader_data(), new_jmeths);
2494 }
2495 }
2496
2497 // Lookup a jmethodID, null if not found. Do no blocking, no allocations, no handles
2498 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
2499 int idnum = method->method_idnum();
2500 jmethodID* jmeths = methods_jmethod_ids_acquire();
2501 return (jmeths != nullptr) ? jmeths[idnum + 1] : nullptr;
2502 }
2503
2504 inline DependencyContext InstanceKlass::dependencies() {
2505 DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);
2506 return dep_context;
2507 }
2508
2509 void InstanceKlass::mark_dependent_nmethods(DeoptimizationScope* deopt_scope, KlassDepChange& changes) {
2510 dependencies().mark_dependent_nmethods(deopt_scope, changes, this);
2511 }
2512
2513 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2514 dependencies().add_dependent_nmethod(nm);
2515 }
2516
2517 void InstanceKlass::clean_dependency_context() {
2518 dependencies().clean_unloading_dependents();
2519 }
2520
2521 #ifndef PRODUCT
2522 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2523 dependencies().print_dependent_nmethods(verbose);
2524 }
2525
2526 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2527 return dependencies().is_dependent_nmethod(nm);
2528 }
2529 #endif //PRODUCT
2530
2619 if (itable_length() > 0) {
2620 itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2621 int method_table_offset_in_words = ioe->offset()/wordSize;
2622 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2623
2624 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2625 / itableOffsetEntry::size();
2626
2627 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2628 if (ioe->interface_klass() != nullptr) {
2629 it->push(ioe->interface_klass_addr());
2630 itableMethodEntry* ime = ioe->first_method_entry(this);
2631 int n = klassItable::method_count_for_interface(ioe->interface_klass());
2632 for (int index = 0; index < n; index ++) {
2633 it->push(ime[index].method_addr());
2634 }
2635 }
2636 }
2637 }
2638
2639 it->push(&_nest_host);
2640 it->push(&_nest_members);
2641 it->push(&_permitted_subclasses);
2642 it->push(&_record_components);
2643 }
2644
2645 #if INCLUDE_CDS
2646 void InstanceKlass::remove_unshareable_info() {
2647 if (is_linked()) {
2648 assert(can_be_verified_at_dumptime(), "must be");
2649 // Remember this so we can avoid walking the hierarchy at runtime.
2650 set_verified_at_dump_time();
2651 }
2652 _misc_flags.set_has_init_deps_processed(false);
2653
2654 Klass::remove_unshareable_info();
2655
2656 if (SystemDictionaryShared::has_class_failed_verification(this)) {
2657 // Classes are attempted to link during dumping and may fail,
2658 // but these classes are still in the dictionary and class list in CLD.
2659 // If the class has failed verification, there is nothing else to remove.
2660 return;
2661 }
2662
2663 // Reset to the 'allocated' state to prevent any premature accessing to
2664 // a shared class at runtime while the class is still being loaded and
2665 // restored. A class' init_state is set to 'loaded' at runtime when it's
2666 // being added to class hierarchy (see InstanceKlass:::add_to_hierarchy()).
2667 _init_state = allocated;
2668
2669 { // Otherwise this needs to take out the Compile_lock.
2670 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2671 init_implementor();
2672 }
2683 // do array classes also.
2684 if (array_klasses() != nullptr) {
2685 array_klasses()->remove_unshareable_info();
2686 }
2687
2688 // These are not allocated from metaspace. They are safe to set to null.
2689 _source_debug_extension = nullptr;
2690 _dep_context = nullptr;
2691 _osr_nmethods_head = nullptr;
2692 #if INCLUDE_JVMTI
2693 _breakpoints = nullptr;
2694 _previous_versions = nullptr;
2695 _cached_class_file = nullptr;
2696 _jvmti_cached_class_field_map = nullptr;
2697 #endif
2698
2699 _init_thread = nullptr;
2700 _methods_jmethod_ids = nullptr;
2701 _jni_ids = nullptr;
2702 _oop_map_cache = nullptr;
2703 if (CDSConfig::is_dumping_invokedynamic() && HeapShared::is_lambda_proxy_klass(this)) {
2704 // keep _nest_host
2705 } else {
2706 // clear _nest_host to ensure re-load at runtime
2707 _nest_host = nullptr;
2708 }
2709 init_shared_package_entry();
2710 _dep_context_last_cleaned = 0;
2711 DEBUG_ONLY(_shared_class_load_count = 0);
2712
2713 remove_unshareable_flags();
2714 }
2715
2716 void InstanceKlass::remove_unshareable_flags() {
2717 // clear all the flags/stats that shouldn't be in the archived version
2718 assert(!is_scratch_class(), "must be");
2719 assert(!has_been_redefined(), "must be");
2720 #if INCLUDE_JVMTI
2721 set_is_being_redefined(false);
2722 #endif
2723 set_has_resolved_methods(false);
2724 }
2725
2726 void InstanceKlass::remove_java_mirror() {
2727 Klass::remove_java_mirror();
2728
2729 // do array classes also.
2730 if (array_klasses() != nullptr) {
2731 array_klasses()->remove_java_mirror();
2797
2798 // restore constant pool resolved references
2799 constants()->restore_unshareable_info(CHECK);
2800
2801 if (array_klasses() != nullptr) {
2802 // To get a consistent list of classes we need MultiArray_lock to ensure
2803 // array classes aren't observed while they are being restored.
2804 RecursiveLocker rl(MultiArray_lock, THREAD);
2805 assert(this == array_klasses()->bottom_klass(), "sanity");
2806 // Array classes have null protection domain.
2807 // --> see ArrayKlass::complete_create_array_klass()
2808 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
2809 }
2810
2811 // Initialize @ValueBased class annotation
2812 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation()) {
2813 set_is_value_based();
2814 }
2815 }
2816
2817 bool InstanceKlass::can_be_verified_at_dumptime() const {
2818 if (CDSConfig::preserve_all_dumptime_verification_states(this)) {
2819 return true;
2820 }
2821
2822 if (MetaspaceShared::is_in_shared_metaspace(this)) {
2823 // This is a class that was dumped into the base archive, so we know
2824 // it was verified at dump time.
2825 return true;
2826 }
2827
2828 if (CDSConfig::is_dumping_invokedynamic()) {
2829 // FIXME: this works around JDK-8315719
2830 return true;
2831 }
2832
2833 // Check if a class or any of its supertypes has a version older than 50.
2834 // CDS will not perform verification of old classes during dump time because
2835 // without changing the old verifier, the verification constraint cannot be
2836 // retrieved during dump time.
2837 // Verification of archived old classes will be performed during run time.
2838 if (major_version() < 50 /*JAVA_6_VERSION*/) {
2839 return false;
2840 }
2841 if (java_super() != nullptr && !java_super()->can_be_verified_at_dumptime()) {
2842 return false;
2843 }
2844 Array<InstanceKlass*>* interfaces = local_interfaces();
2845 int len = interfaces->length();
2846 for (int i = 0; i < len; i++) {
2847 if (!interfaces->at(i)->can_be_verified_at_dumptime()) {
2848 return false;
2849 }
2850 }
2851 return true;
2852 }
2853
2854 bool InstanceKlass::methods_contain_jsr_bytecode() const {
2855 Thread* thread = Thread::current();
2856 for (int i = 0; i < _methods->length(); i++) {
2857 methodHandle m(thread, _methods->at(i));
2858 BytecodeStream bcs(m);
2859 while (!bcs.is_last_bytecode()) {
2860 Bytecodes::Code opcode = bcs.next();
2861 if (opcode == Bytecodes::_jsr || opcode == Bytecodes::_jsr_w) {
2862 return true;
2863 }
2864 }
2865 }
2866 return false;
2867 }
2868
2869 int InstanceKlass::shared_class_loader_type() const {
2870 if (is_shared_boot_class()) {
2871 return ClassLoader::BOOT_LOADER;
2872 } else if (is_shared_platform_class()) {
2873 return ClassLoader::PLATFORM_LOADER;
2874 } else if (is_shared_app_class()) {
2875 return ClassLoader::APP_LOADER;
2876 } else {
2877 return ClassLoader::OTHER;
2878 }
2879 }
2880 #endif // INCLUDE_CDS
2881
2882 #if INCLUDE_JVMTI
2883 static void clear_all_breakpoints(Method* m) {
2884 m->clear_all_breakpoints();
2885 }
2886 #endif
2887
2888 void InstanceKlass::unload_class(InstanceKlass* ik) {
2889 // Release dependencies.
2890 ik->dependencies().remove_all_dependents();
2891
2892 // notify the debugger
2893 if (JvmtiExport::should_post_class_unload()) {
2894 JvmtiExport::post_class_unload(ik);
2895 }
2896
2897 // notify ClassLoadingService of class unload
2898 ClassLoadingService::notify_class_unloaded(ik);
2899
3626 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3627 for (int i = 0; i < len; i++) {
3628 intptr_t e = start[i];
3629 st->print("%d : " INTPTR_FORMAT, i, e);
3630 if (MetaspaceObj::is_valid((Metadata*)e)) {
3631 st->print(" ");
3632 ((Metadata*)e)->print_value_on(st);
3633 }
3634 st->cr();
3635 }
3636 }
3637
3638 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3639 return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3640 }
3641
3642 const char* InstanceKlass::init_state_name() const {
3643 return state_names[init_state()];
3644 }
3645
3646 const char* InstanceKlass::state2name(ClassState s) {
3647 return state_names[s];
3648 }
3649
3650 void InstanceKlass::print_on(outputStream* st) const {
3651 assert(is_klass(), "must be klass");
3652 Klass::print_on(st);
3653
3654 st->print(BULLET"instance size: %d", size_helper()); st->cr();
3655 st->print(BULLET"klass size: %d", size()); st->cr();
3656 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
3657 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
3658 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
3659 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
3660 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3661 st->print(BULLET"sub: ");
3662 Klass* sub = subklass();
3663 int n;
3664 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3665 if (n < MaxSubklassPrintSize) {
3666 sub->print_value_on(st);
3667 st->print(" ");
3668 }
3669 }
3959 nullptr;
3960 // caller can be null, for example, during a JVMTI VM_Init hook
3961 if (caller != nullptr) {
3962 info_stream.print(" source: instance of %s", caller->external_name());
3963 } else {
3964 // source is unknown
3965 }
3966 } else {
3967 oop class_loader = loader_data->class_loader();
3968 info_stream.print(" source: %s", class_loader->klass()->external_name());
3969 }
3970 } else {
3971 assert(this->is_shared(), "must be");
3972 if (MetaspaceShared::is_shared_dynamic((void*)this)) {
3973 info_stream.print(" source: shared objects file (top)");
3974 } else {
3975 info_stream.print(" source: shared objects file");
3976 }
3977 }
3978
3979 info_stream.print(" loader:");
3980 if (is_shared()) {
3981 info_stream.print(" %s", SystemDictionaryShared::class_loader_name_for_shared((Klass*)this));
3982 } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) {
3983 info_stream.print(" boot_loader");
3984 } else {
3985 oop class_loader = loader_data->class_loader();
3986 if (class_loader != nullptr) {
3987 info_stream.print(" %s", class_loader->klass()->external_name());
3988 oop cl_name_and_id = java_lang_ClassLoader::nameAndId(class_loader);
3989 if (cl_name_and_id != nullptr) {
3990 info_stream.print(" %s", java_lang_String::as_utf8_string(cl_name_and_id));
3991 }
3992 } else {
3993 info_stream.print(" null");
3994 }
3995 }
3996 msg.info("%s", info_stream.as_string());
3997
3998 if (log_is_enabled(Debug, class, load)) {
3999 stringStream debug_stream;
4000
4001 // Class hierarchy info
4002 debug_stream.print(" klass: " PTR_FORMAT " super: " PTR_FORMAT,
4003 p2i(this), p2i(superklass()));
4004
4005 // Interfaces
4006 if (local_interfaces() != nullptr && local_interfaces()->length() > 0) {
4007 debug_stream.print(" interfaces:");
4008 int length = local_interfaces()->length();
4009 for (int i = 0; i < length; i++) {
4010 debug_stream.print(" " PTR_FORMAT,
4011 p2i(InstanceKlass::cast(local_interfaces()->at(i))));
4012 }
4013 }
4014
4015 // Class loader
|