< prev index next >

src/hotspot/share/oops/instanceKlass.cpp

Print this page

  28 #include "cds/cdsConfig.hpp"
  29 #include "cds/cdsEnumKlass.hpp"
  30 #include "cds/classListWriter.hpp"
  31 #include "cds/heapShared.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 "klass.inline.hpp"
  54 #include "logging/log.hpp"
  55 #include "logging/logMessage.hpp"
  56 #include "logging/logStream.hpp"
  57 #include "memory/allocation.inline.hpp"
  58 #include "memory/iterator.inline.hpp"
  59 #include "memory/metadataFactory.hpp"
  60 #include "memory/metaspaceClosure.hpp"
  61 #include "memory/oopFactory.hpp"
  62 #include "memory/resourceArea.hpp"
  63 #include "memory/universe.hpp"
  64 #include "oops/constantPool.hpp"
  65 #include "oops/fieldStreams.inline.hpp"
  66 #include "oops/instanceClassLoaderKlass.hpp"
  67 #include "oops/instanceKlass.inline.hpp"

  71 #include "oops/klass.inline.hpp"
  72 #include "oops/method.hpp"
  73 #include "oops/oop.inline.hpp"
  74 #include "oops/recordComponent.hpp"
  75 #include "oops/symbol.hpp"
  76 #include "prims/jvmtiExport.hpp"
  77 #include "prims/jvmtiRedefineClasses.hpp"
  78 #include "prims/jvmtiThreadState.hpp"
  79 #include "prims/methodComparator.hpp"
  80 #include "runtime/arguments.hpp"
  81 #include "runtime/atomicAccess.hpp"
  82 #include "runtime/deoptimization.hpp"
  83 #include "runtime/fieldDescriptor.inline.hpp"
  84 #include "runtime/handles.inline.hpp"
  85 #include "runtime/javaCalls.hpp"
  86 #include "runtime/javaThread.inline.hpp"
  87 #include "runtime/mutexLocker.hpp"
  88 #include "runtime/orderAccess.hpp"
  89 #include "runtime/os.inline.hpp"
  90 #include "runtime/reflection.hpp"

  91 #include "runtime/synchronizer.hpp"
  92 #include "runtime/threads.hpp"
  93 #include "services/classLoadingService.hpp"
  94 #include "services/finalizerService.hpp"
  95 #include "services/threadService.hpp"
  96 #include "utilities/dtrace.hpp"
  97 #include "utilities/events.hpp"
  98 #include "utilities/macros.hpp"
  99 #include "utilities/nativeStackPrinter.hpp"
 100 #include "utilities/stringUtils.hpp"
 101 #ifdef COMPILER1
 102 #include "c1/c1_Compiler.hpp"
 103 #endif
 104 #if INCLUDE_JFR
 105 #include "jfr/jfrEvents.hpp"
 106 #endif
 107 
 108 #ifdef DTRACE_ENABLED
 109 
 110 

1061   return true;
1062 }
1063 
1064 // Rewrite the byte codes of all of the methods of a class.
1065 // The rewriter must be called exactly once. Rewriting must happen after
1066 // verification but before the first method of the class is executed.
1067 void InstanceKlass::rewrite_class(TRAPS) {
1068   assert(is_loaded(), "must be loaded");
1069   if (is_rewritten()) {
1070     assert(in_aot_cache(), "rewriting an unshared class?");
1071     return;
1072   }
1073   Rewriter::rewrite(this, CHECK);
1074   set_rewritten();
1075 }
1076 
1077 // Now relocate and link method entry points after class is rewritten.
1078 // This is outside is_rewritten flag. In case of an exception, it can be
1079 // executed more than once.
1080 void InstanceKlass::link_methods(TRAPS) {
1081   PerfTraceTime timer(ClassLoader::perf_ik_link_methods_time());
1082 
1083   int len = methods()->length();
1084   for (int i = len-1; i >= 0; i--) {
1085     methodHandle m(THREAD, methods()->at(i));

1086 
1087     // Set up method entry points for compiler and interpreter    .
1088     m->link_method(m, CHECK);
1089   }
1090 }
1091 
1092 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
1093 void InstanceKlass::initialize_super_interfaces(TRAPS) {
1094   assert (has_nonstatic_concrete_methods(), "caller should have checked this");
1095   for (int i = 0; i < local_interfaces()->length(); ++i) {
1096     InstanceKlass* ik = local_interfaces()->at(i);
1097 
1098     // Initialization is depth first search ie. we start with top of the inheritance tree
1099     // has_nonstatic_concrete_methods drives searching superinterfaces since it
1100     // means has_nonstatic_concrete_methods in its superinterface hierarchy
1101     if (ik->has_nonstatic_concrete_methods()) {
1102       ik->initialize_super_interfaces(CHECK);
1103     }
1104 
1105     // Only initialize() interfaces that "declare" concrete methods.

1170   assert_locked_or_safepoint(ClassInitError_lock);
1171   InitErrorTableCleaner cleaner;
1172   if (_initialization_error_table != nullptr) {
1173     _initialization_error_table->unlink(&cleaner);
1174   }
1175 }
1176 
1177 void InstanceKlass::initialize_impl(TRAPS) {
1178   HandleMark hm(THREAD);
1179 
1180   // Make sure klass is linked (verified) before initialization
1181   // A class could already be verified, since it has been reflected upon.
1182   link_class(CHECK);
1183 
1184   DTRACE_CLASSINIT_PROBE(required, -1);
1185 
1186   bool wait = false;
1187 
1188   JavaThread* jt = THREAD;
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);

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 
1360 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1361   Handle h_init_lock(THREAD, init_lock());
1362   if (h_init_lock() != nullptr) {
1363     ObjectLocker ol(h_init_lock, THREAD);
1364     set_init_thread(nullptr); // reset _init_thread before changing _init_state
1365     set_init_state(state);
1366     fence_and_clear_init_lock();
1367     ol.notify_all(CHECK);
1368   } else {
1369     assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1370     set_init_thread(nullptr); // reset _init_thread before changing _init_state
1371     set_init_state(state);
1372   }
1373 }
1374 
1375 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1376 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1377 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1378   assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1379 

1569     tty->print("Registered ");
1570     i->print_value_on(tty);
1571     tty->print_cr(" (" PTR_FORMAT ") as finalizable", p2i(i));
1572   }
1573   instanceHandle h_i(THREAD, i);
1574   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1575   JavaValue result(T_VOID);
1576   JavaCallArguments args(h_i);
1577   methodHandle mh(THREAD, Universe::finalizer_register_method());
1578   JavaCalls::call(&result, mh, &args, CHECK_NULL);
1579   MANAGEMENT_ONLY(FinalizerService::on_register(h_i(), THREAD);)
1580   return h_i();
1581 }
1582 
1583 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1584   assert(!is_abstract() && !is_interface(), "Should not create this object");
1585   size_t size = size_helper();  // Query before forming handle.
1586   return (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);
1587 }
1588 
1589 instanceOop InstanceKlass::allocate_instance(oop java_class, TRAPS) {


1590   Klass* k = java_lang_Class::as_Klass(java_class);
1591   if (k == nullptr) {
1592     ResourceMark rm(THREAD);
1593     THROW_(vmSymbols::java_lang_InstantiationException(), nullptr);
1594   }
1595   InstanceKlass* ik = cast(k);
1596   ik->check_valid_for_instantiation(false, CHECK_NULL);
1597   ik->initialize(CHECK_NULL);
1598   return ik->allocate_instance(THREAD);
1599 }
1600 
1601 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1602   return instanceHandle(THREAD, allocate_instance(THREAD));
1603 }
1604 
1605 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1606   if (is_interface() || is_abstract()) {
1607     ResourceMark rm(THREAD);
1608     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1609               : vmSymbols::java_lang_InstantiationException(), external_name());

1672     // Hide the existence of the initializer for the purpose of replaying the compile
1673     return;
1674   }
1675 
1676 #if INCLUDE_CDS
1677   // This is needed to ensure the consistency of the archived heap objects.
1678   if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
1679     AOTClassInitializer::call_runtime_setup(THREAD, this);
1680     return;
1681   } else if (has_archived_enum_objs()) {
1682     assert(in_aot_cache(), "must be");
1683     bool initialized = CDSEnumKlass::initialize_enum_klass(this, CHECK);
1684     if (initialized) {
1685       return;
1686     }
1687   }
1688 #endif
1689 
1690   methodHandle h_method(THREAD, class_initializer());
1691   assert(!is_initialized(), "we cannot initialize twice");






















































1692   LogTarget(Info, class, init) lt;
1693   if (lt.is_enabled()) {
1694     ResourceMark rm(THREAD);
1695     LogStream ls(lt);
1696     ls.print("%d Initializing ", call_class_initializer_counter++);
1697     name()->print_value_on(&ls);
1698     ls.print_cr("%s (" PTR_FORMAT ") by thread \"%s\"",
1699                 h_method() == nullptr ? "(no method)" : "", p2i(this),
1700                 THREAD->name());
1701   }
1702   if (h_method() != nullptr) {
1703     ThreadInClassInitializer ticl(THREAD, this); // Track class being initialized
1704     JavaCallArguments args; // No arguments
1705     JavaValue result(T_VOID);
1706     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1707   }

1708 }
1709 
1710 // If a class that implements this interface is initialized, is the JVM required
1711 // to first execute a <clinit> method declared in this interface,
1712 // or (if also_check_supers==true) any of the super types of this interface?
1713 //
1714 // JVMS 5.5. Initialization, step 7: Next, if C is a class rather than
1715 // an interface, then let SC be its superclass and let SI1, ..., SIn
1716 // be all superinterfaces of C (whether direct or indirect) that
1717 // declare at least one non-abstract, non-static method.
1718 //
1719 // So when an interface is initialized, it does not look at its
1720 // supers. But a proper class will ensure that all of its supers have
1721 // run their <clinit> methods, except that it disregards interfaces
1722 // that lack a non-static concrete method (i.e., a default method).
1723 // Therefore, you should probably call this method only when the
1724 // current class is a super of some proper class, not an interface.
1725 bool InstanceKlass::interface_needs_clinit_execution_as_super(bool also_check_supers) const {
1726   assert(is_interface(), "must be");
1727 

2496         id == nullptr) {
2497       id = Method::make_jmethod_id(class_loader_data(), m);
2498       AtomicAccess::release_store(&jmeths[idnum + 1], id);
2499     }
2500   }
2501 }
2502 
2503 // Lookup a jmethodID, null if not found.  Do no blocking, no allocations, no handles
2504 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
2505   int idnum = method->method_idnum();
2506   jmethodID* jmeths = methods_jmethod_ids_acquire();
2507   return (jmeths != nullptr) ? jmeths[idnum + 1] : nullptr;
2508 }
2509 
2510 inline DependencyContext InstanceKlass::dependencies() {
2511   DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);
2512   return dep_context;
2513 }
2514 
2515 void InstanceKlass::mark_dependent_nmethods(DeoptimizationScope* deopt_scope, KlassDepChange& changes) {
2516   dependencies().mark_dependent_nmethods(deopt_scope, changes);
2517 }
2518 
2519 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2520   assert_lock_strong(CodeCache_lock);
2521   dependencies().add_dependent_nmethod(nm);
2522 }
2523 
2524 void InstanceKlass::clean_dependency_context() {
2525   dependencies().clean_unloading_dependents();
2526 }
2527 
2528 #ifndef PRODUCT
2529 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2530   dependencies().print_dependent_nmethods(verbose);
2531 }
2532 
2533 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2534   return dependencies().is_dependent_nmethod(nm);
2535 }
2536 #endif //PRODUCT

2635     for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2636       if (ioe->interface_klass() != nullptr) {
2637         it->push(ioe->interface_klass_addr());
2638         itableMethodEntry* ime = ioe->first_method_entry(this);
2639         int n = klassItable::method_count_for_interface(ioe->interface_klass());
2640         for (int index = 0; index < n; index ++) {
2641           it->push(ime[index].method_addr());
2642         }
2643       }
2644     }
2645   }
2646 
2647   it->push(&_nest_host);
2648   it->push(&_nest_members);
2649   it->push(&_permitted_subclasses);
2650   it->push(&_record_components);
2651 }
2652 
2653 #if INCLUDE_CDS
2654 void InstanceKlass::remove_unshareable_info() {
2655 
2656   if (is_linked()) {
2657     assert(can_be_verified_at_dumptime(), "must be");
2658     // Remember this so we can avoid walking the hierarchy at runtime.
2659     set_verified_at_dump_time();
2660   }
2661 
2662   _misc_flags.set_has_init_deps_processed(false);
2663 
2664   Klass::remove_unshareable_info();
2665 
2666   if (SystemDictionaryShared::has_class_failed_verification(this)) {
2667     // Classes are attempted to link during dumping and may fail,
2668     // but these classes are still in the dictionary and class list in CLD.
2669     // If the class has failed verification, there is nothing else to remove.
2670     return;
2671   }
2672 
2673   // Reset to the 'allocated' state to prevent any premature accessing to
2674   // a shared class at runtime while the class is still being loaded and
2675   // restored. A class' init_state is set to 'loaded' at runtime when it's

3623 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3624   for (int i = 0; i < len; i++) {
3625     intptr_t e = start[i];
3626     st->print("%d : " INTPTR_FORMAT, i, e);
3627     if (MetaspaceObj::is_valid((Metadata*)e)) {
3628       st->print(" ");
3629       ((Metadata*)e)->print_value_on(st);
3630     }
3631     st->cr();
3632   }
3633 }
3634 
3635 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3636   return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3637 }
3638 
3639 const char* InstanceKlass::init_state_name() const {
3640   return state_names[init_state()];
3641 }
3642 




3643 void InstanceKlass::print_on(outputStream* st) const {
3644   assert(is_klass(), "must be klass");
3645   Klass::print_on(st);
3646 
3647   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3648   st->print(BULLET"klass size:        %d", size());                               st->cr();
3649   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
3650   st->print(BULLET"flags:             "); _misc_flags.print_on(st);               st->cr();
3651   st->print(BULLET"state:             "); st->print_cr("%s", init_state_name());
3652   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3653   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3654   st->print(BULLET"sub:               ");
3655   Klass* sub = subklass();
3656   int n;
3657   for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3658     if (n < MaxSubklassPrintSize) {
3659       sub->print_value_on(st);
3660       st->print("   ");
3661     }
3662   }

3957         nullptr;
3958       // caller can be null, for example, during a JVMTI VM_Init hook
3959       if (caller != nullptr) {
3960         info_stream.print(" source: instance of %s", caller->external_name());
3961       } else {
3962         // source is unknown
3963       }
3964     } else {
3965       oop class_loader = loader_data->class_loader();
3966       info_stream.print(" source: %s", class_loader->klass()->external_name());
3967     }
3968   } else {
3969     assert(this->in_aot_cache(), "must be");
3970     if (AOTMetaspace::in_aot_cache_dynamic_region((void*)this)) {
3971       info_stream.print(" source: shared objects file (top)");
3972     } else {
3973       info_stream.print(" source: shared objects file");
3974     }
3975   }
3976 




















3977   msg.info("%s", info_stream.as_string());
3978 
3979   if (log_is_enabled(Debug, class, load)) {
3980     stringStream debug_stream;
3981 
3982     // Class hierarchy info
3983     debug_stream.print(" klass: " PTR_FORMAT " super: " PTR_FORMAT,
3984                        p2i(this),  p2i(super()));
3985 
3986     // Interfaces
3987     if (local_interfaces() != nullptr && local_interfaces()->length() > 0) {
3988       debug_stream.print(" interfaces:");
3989       int length = local_interfaces()->length();
3990       for (int i = 0; i < length; i++) {
3991         debug_stream.print(" " PTR_FORMAT,
3992                            p2i(local_interfaces()->at(i)));
3993       }
3994     }
3995 
3996     // Class loader

  28 #include "cds/cdsConfig.hpp"
  29 #include "cds/cdsEnumKlass.hpp"
  30 #include "cds/classListWriter.hpp"
  31 #include "cds/heapShared.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 "klass.inline.hpp"
  55 #include "logging/log.hpp"
  56 #include "logging/logMessage.hpp"
  57 #include "logging/logStream.hpp"
  58 #include "memory/allocation.inline.hpp"
  59 #include "memory/iterator.inline.hpp"
  60 #include "memory/metadataFactory.hpp"
  61 #include "memory/metaspaceClosure.hpp"
  62 #include "memory/oopFactory.hpp"
  63 #include "memory/resourceArea.hpp"
  64 #include "memory/universe.hpp"
  65 #include "oops/constantPool.hpp"
  66 #include "oops/fieldStreams.inline.hpp"
  67 #include "oops/instanceClassLoaderKlass.hpp"
  68 #include "oops/instanceKlass.inline.hpp"

  72 #include "oops/klass.inline.hpp"
  73 #include "oops/method.hpp"
  74 #include "oops/oop.inline.hpp"
  75 #include "oops/recordComponent.hpp"
  76 #include "oops/symbol.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/atomicAccess.hpp"
  83 #include "runtime/deoptimization.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/runtimeUpcalls.hpp"
  93 #include "runtime/synchronizer.hpp"
  94 #include "runtime/threads.hpp"
  95 #include "services/classLoadingService.hpp"
  96 #include "services/finalizerService.hpp"
  97 #include "services/threadService.hpp"
  98 #include "utilities/dtrace.hpp"
  99 #include "utilities/events.hpp"
 100 #include "utilities/macros.hpp"
 101 #include "utilities/nativeStackPrinter.hpp"
 102 #include "utilities/stringUtils.hpp"
 103 #ifdef COMPILER1
 104 #include "c1/c1_Compiler.hpp"
 105 #endif
 106 #if INCLUDE_JFR
 107 #include "jfr/jfrEvents.hpp"
 108 #endif
 109 
 110 #ifdef DTRACE_ENABLED
 111 
 112 

1063   return true;
1064 }
1065 
1066 // Rewrite the byte codes of all of the methods of a class.
1067 // The rewriter must be called exactly once. Rewriting must happen after
1068 // verification but before the first method of the class is executed.
1069 void InstanceKlass::rewrite_class(TRAPS) {
1070   assert(is_loaded(), "must be loaded");
1071   if (is_rewritten()) {
1072     assert(in_aot_cache(), "rewriting an unshared class?");
1073     return;
1074   }
1075   Rewriter::rewrite(this, CHECK);
1076   set_rewritten();
1077 }
1078 
1079 // Now relocate and link method entry points after class is rewritten.
1080 // This is outside is_rewritten flag. In case of an exception, it can be
1081 // executed more than once.
1082 void InstanceKlass::link_methods(TRAPS) {
1083   PerfTraceElapsedTime timer(ClassLoader::perf_ik_link_methods_time());
1084 
1085   int len = methods()->length();
1086   for (int i = len-1; i >= 0; i--) {
1087     methodHandle m(THREAD, methods()->at(i));
1088     RuntimeUpcalls::install_upcalls(m);
1089 
1090     // Set up method entry points for compiler and interpreter    .
1091     m->link_method(m, CHECK);
1092   }
1093 }
1094 
1095 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
1096 void InstanceKlass::initialize_super_interfaces(TRAPS) {
1097   assert (has_nonstatic_concrete_methods(), "caller should have checked this");
1098   for (int i = 0; i < local_interfaces()->length(); ++i) {
1099     InstanceKlass* ik = local_interfaces()->at(i);
1100 
1101     // Initialization is depth first search ie. we start with top of the inheritance tree
1102     // has_nonstatic_concrete_methods drives searching superinterfaces since it
1103     // means has_nonstatic_concrete_methods in its superinterface hierarchy
1104     if (ik->has_nonstatic_concrete_methods()) {
1105       ik->initialize_super_interfaces(CHECK);
1106     }
1107 
1108     // Only initialize() interfaces that "declare" concrete methods.

1173   assert_locked_or_safepoint(ClassInitError_lock);
1174   InitErrorTableCleaner cleaner;
1175   if (_initialization_error_table != nullptr) {
1176     _initialization_error_table->unlink(&cleaner);
1177   }
1178 }
1179 
1180 void InstanceKlass::initialize_impl(TRAPS) {
1181   HandleMark hm(THREAD);
1182 
1183   // Make sure klass is linked (verified) before initialization
1184   // A class could already be verified, since it has been reflected upon.
1185   link_class(CHECK);
1186 
1187   DTRACE_CLASSINIT_PROBE(required, -1);
1188 
1189   bool wait = false;
1190 
1191   JavaThread* jt = THREAD;
1192 
1193   if (ForceProfiling) {
1194     // Preallocate MDOs.
1195     for (int i = 0; i < methods()->length(); i++) {
1196       assert(!HAS_PENDING_EXCEPTION, "");
1197       methodHandle m(THREAD, methods()->at(i));
1198       Method::build_profiling_method_data(m, THREAD);
1199       if (HAS_PENDING_EXCEPTION) {
1200         ResourceMark rm;
1201         log_warning(cds)("MDO preallocation failed for %s", external_name());
1202         CLEAR_PENDING_EXCEPTION;
1203         break;
1204       }
1205     }
1206   }
1207 
1208   bool debug_logging_enabled = log_is_enabled(Debug, class, init);
1209 
1210   // refer to the JVM book page 47 for description of steps
1211   // Step 1
1212   {
1213     Handle h_init_lock(THREAD, init_lock());
1214     ObjectLocker ol(h_init_lock, jt);
1215 
1216     // Step 2
1217     // If we were to use wait() instead of waitInterruptibly() then
1218     // we might end up throwing IE from link/symbol resolution sites
1219     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
1220     while (is_being_initialized() && !is_reentrant_initialization(jt)) {
1221       if (debug_logging_enabled) {
1222         ResourceMark rm(jt);
1223         log_debug(class, init)("Thread \"%s\" waiting for initialization of %s by thread \"%s\"",
1224                                jt->name(), external_name(), init_thread_name());
1225       }
1226       wait = true;
1227       jt->set_class_to_be_initialized(this);

1357       add_initialization_error(THREAD, e);
1358       set_initialization_state_and_notify(initialization_error, THREAD);
1359       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
1360       // JVMTI has already reported the pending exception
1361       // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1362       JvmtiExport::clear_detected_exception(jt);
1363     }
1364     DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1365     if (e->is_a(vmClasses::Error_klass())) {
1366       THROW_OOP(e());
1367     } else {
1368       JavaCallArguments args(e);
1369       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
1370                 vmSymbols::throwable_void_signature(),
1371                 &args);
1372     }
1373   }
1374   DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1375 }
1376 

1377 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1378   Handle h_init_lock(THREAD, init_lock());
1379   if (h_init_lock() != nullptr) {
1380     ObjectLocker ol(h_init_lock, THREAD);
1381     set_init_thread(nullptr); // reset _init_thread before changing _init_state
1382     set_init_state(state);
1383     fence_and_clear_init_lock();
1384     ol.notify_all(CHECK);
1385   } else {
1386     assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1387     set_init_thread(nullptr); // reset _init_thread before changing _init_state
1388     set_init_state(state);
1389   }
1390 }
1391 
1392 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1393 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1394 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1395   assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1396 

1586     tty->print("Registered ");
1587     i->print_value_on(tty);
1588     tty->print_cr(" (" PTR_FORMAT ") as finalizable", p2i(i));
1589   }
1590   instanceHandle h_i(THREAD, i);
1591   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1592   JavaValue result(T_VOID);
1593   JavaCallArguments args(h_i);
1594   methodHandle mh(THREAD, Universe::finalizer_register_method());
1595   JavaCalls::call(&result, mh, &args, CHECK_NULL);
1596   MANAGEMENT_ONLY(FinalizerService::on_register(h_i(), THREAD);)
1597   return h_i();
1598 }
1599 
1600 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1601   assert(!is_abstract() && !is_interface(), "Should not create this object");
1602   size_t size = size_helper();  // Query before forming handle.
1603   return (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);
1604 }
1605 
1606 instanceOop InstanceKlass::allocate_instance(oop java_class,
1607                                              const char* who,
1608                                              TRAPS) {
1609   Klass* k = java_lang_Class::as_Klass(java_class);
1610   if (k == nullptr) {
1611     ResourceMark rm(THREAD);
1612     THROW_(vmSymbols::java_lang_InstantiationException(), nullptr);
1613   }
1614   InstanceKlass* ik = cast(k);
1615   ik->check_valid_for_instantiation(false, CHECK_NULL);
1616   ik->initialize(CHECK_NULL);
1617   return ik->allocate_instance(THREAD);
1618 }
1619 
1620 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1621   return instanceHandle(THREAD, allocate_instance(THREAD));
1622 }
1623 
1624 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1625   if (is_interface() || is_abstract()) {
1626     ResourceMark rm(THREAD);
1627     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1628               : vmSymbols::java_lang_InstantiationException(), external_name());

1691     // Hide the existence of the initializer for the purpose of replaying the compile
1692     return;
1693   }
1694 
1695 #if INCLUDE_CDS
1696   // This is needed to ensure the consistency of the archived heap objects.
1697   if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
1698     AOTClassInitializer::call_runtime_setup(THREAD, this);
1699     return;
1700   } else if (has_archived_enum_objs()) {
1701     assert(in_aot_cache(), "must be");
1702     bool initialized = CDSEnumKlass::initialize_enum_klass(this, CHECK);
1703     if (initialized) {
1704       return;
1705     }
1706   }
1707 #endif
1708 
1709   methodHandle h_method(THREAD, class_initializer());
1710   assert(!is_initialized(), "we cannot initialize twice");
1711 
1712 #if 0
1713   // FIXME -- revive this code added to leyden/premain for <clinit> profiling
1714   int init_id = log_class_init(THREAD, this);
1715   if (h_method() != nullptr) {
1716     JavaCallArguments args; // No arguments
1717     JavaValue result(T_VOID);
1718     InstanceKlass* outer = THREAD->set_class_being_initialized(this);
1719     jlong bc_start = (CountBytecodesPerThread ? THREAD->bc_counter_value() : BytecodeCounter::counter_value());
1720 
1721     elapsedTimer timer;
1722     {
1723       PerfPauseTimer pt(THREAD->current_rt_call_timer(), THREAD->profile_rt_calls());
1724       PauseRuntimeCallProfiling prcp(THREAD, THREAD->profile_rt_calls());
1725 
1726       timer.start();
1727       JavaCalls::call(&result, h_method, &args, THREAD); // Static call (no args)
1728       timer.stop();
1729     }
1730 
1731     jlong bc_end = (CountBytecodesPerThread ? THREAD->bc_counter_value() : BytecodeCounter::counter_value());
1732 
1733     jlong bc_executed = (bc_end - bc_start);
1734     if (UsePerfData && outer == nullptr) { // outermost clinit
1735       THREAD->inc_clinit_bc_counter_value(bc_executed);
1736       ClassLoader::perf_class_init_bytecodes_count()->inc(bc_executed);
1737     }
1738 
1739     THREAD->set_class_being_initialized(outer);
1740 
1741     LogStreamHandle(Debug, init) log;
1742     if (log.is_enabled()) {
1743       ResourceMark rm(THREAD);
1744       log.print("%d Initialized in %.3fms (total: " JLONG_FORMAT "ms); ",
1745                 init_id, timer.seconds() * 1000.0, ClassLoader::class_init_time_ms());
1746       if (CountBytecodes || CountBytecodesPerThread) {
1747         log.print("executed " JLONG_FORMAT " bytecodes; ", bc_executed);
1748       }
1749       name()->print_value_on(&log);
1750       log.print_cr(" by thread " PTR_FORMAT " \"%s\" (" PTR_FORMAT ")",
1751                    p2i(THREAD), THREAD->name(), p2i(this));
1752     }
1753   }
1754   LogTarget(Info, class, init) lt;
1755   if (lt.is_enabled()) {
1756     ResourceMark rm(THREAD);
1757     LogStream ls(lt);
1758     ls.print("%d Initialized ", init_id);
1759     name()->print_value_on(&ls);
1760     ls.print_cr("%s (" PTR_FORMAT ") by thread \"%s\"",
1761                 h_method() == nullptr ? "(no method)" : "", p2i(this),
1762                 THREAD->name());
1763   }
1764 #else
1765   LogTarget(Info, class, init) lt;
1766   if (lt.is_enabled()) {
1767     ResourceMark rm(THREAD);
1768     LogStream ls(lt);
1769     ls.print("%d Initializing ", call_class_initializer_counter++);
1770     name()->print_value_on(&ls);
1771     ls.print_cr("%s (" PTR_FORMAT ") by thread \"%s\"",
1772                 h_method() == nullptr ? "(no method)" : "", p2i(this),
1773                 THREAD->name());
1774   }
1775   if (h_method() != nullptr) {
1776     ThreadInClassInitializer ticl(THREAD, this); // Track class being initialized
1777     JavaCallArguments args; // No arguments
1778     JavaValue result(T_VOID);
1779     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1780   }
1781 #endif
1782 }
1783 
1784 // If a class that implements this interface is initialized, is the JVM required
1785 // to first execute a <clinit> method declared in this interface,
1786 // or (if also_check_supers==true) any of the super types of this interface?
1787 //
1788 // JVMS 5.5. Initialization, step 7: Next, if C is a class rather than
1789 // an interface, then let SC be its superclass and let SI1, ..., SIn
1790 // be all superinterfaces of C (whether direct or indirect) that
1791 // declare at least one non-abstract, non-static method.
1792 //
1793 // So when an interface is initialized, it does not look at its
1794 // supers. But a proper class will ensure that all of its supers have
1795 // run their <clinit> methods, except that it disregards interfaces
1796 // that lack a non-static concrete method (i.e., a default method).
1797 // Therefore, you should probably call this method only when the
1798 // current class is a super of some proper class, not an interface.
1799 bool InstanceKlass::interface_needs_clinit_execution_as_super(bool also_check_supers) const {
1800   assert(is_interface(), "must be");
1801 

2570         id == nullptr) {
2571       id = Method::make_jmethod_id(class_loader_data(), m);
2572       AtomicAccess::release_store(&jmeths[idnum + 1], id);
2573     }
2574   }
2575 }
2576 
2577 // Lookup a jmethodID, null if not found.  Do no blocking, no allocations, no handles
2578 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
2579   int idnum = method->method_idnum();
2580   jmethodID* jmeths = methods_jmethod_ids_acquire();
2581   return (jmeths != nullptr) ? jmeths[idnum + 1] : nullptr;
2582 }
2583 
2584 inline DependencyContext InstanceKlass::dependencies() {
2585   DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);
2586   return dep_context;
2587 }
2588 
2589 void InstanceKlass::mark_dependent_nmethods(DeoptimizationScope* deopt_scope, KlassDepChange& changes) {
2590   dependencies().mark_dependent_nmethods(deopt_scope, changes, this);
2591 }
2592 
2593 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2594   assert_lock_strong(CodeCache_lock);
2595   dependencies().add_dependent_nmethod(nm);
2596 }
2597 
2598 void InstanceKlass::clean_dependency_context() {
2599   dependencies().clean_unloading_dependents();
2600 }
2601 
2602 #ifndef PRODUCT
2603 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2604   dependencies().print_dependent_nmethods(verbose);
2605 }
2606 
2607 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2608   return dependencies().is_dependent_nmethod(nm);
2609 }
2610 #endif //PRODUCT

2709     for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2710       if (ioe->interface_klass() != nullptr) {
2711         it->push(ioe->interface_klass_addr());
2712         itableMethodEntry* ime = ioe->first_method_entry(this);
2713         int n = klassItable::method_count_for_interface(ioe->interface_klass());
2714         for (int index = 0; index < n; index ++) {
2715           it->push(ime[index].method_addr());
2716         }
2717       }
2718     }
2719   }
2720 
2721   it->push(&_nest_host);
2722   it->push(&_nest_members);
2723   it->push(&_permitted_subclasses);
2724   it->push(&_record_components);
2725 }
2726 
2727 #if INCLUDE_CDS
2728 void InstanceKlass::remove_unshareable_info() {

2729   if (is_linked()) {
2730     assert(can_be_verified_at_dumptime(), "must be");
2731     // Remember this so we can avoid walking the hierarchy at runtime.
2732     set_verified_at_dump_time();
2733   }
2734 
2735   _misc_flags.set_has_init_deps_processed(false);
2736 
2737   Klass::remove_unshareable_info();
2738 
2739   if (SystemDictionaryShared::has_class_failed_verification(this)) {
2740     // Classes are attempted to link during dumping and may fail,
2741     // but these classes are still in the dictionary and class list in CLD.
2742     // If the class has failed verification, there is nothing else to remove.
2743     return;
2744   }
2745 
2746   // Reset to the 'allocated' state to prevent any premature accessing to
2747   // a shared class at runtime while the class is still being loaded and
2748   // restored. A class' init_state is set to 'loaded' at runtime when it's

3696 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3697   for (int i = 0; i < len; i++) {
3698     intptr_t e = start[i];
3699     st->print("%d : " INTPTR_FORMAT, i, e);
3700     if (MetaspaceObj::is_valid((Metadata*)e)) {
3701       st->print(" ");
3702       ((Metadata*)e)->print_value_on(st);
3703     }
3704     st->cr();
3705   }
3706 }
3707 
3708 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3709   return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3710 }
3711 
3712 const char* InstanceKlass::init_state_name() const {
3713   return state_names[init_state()];
3714 }
3715 
3716 const char* InstanceKlass::state2name(ClassState s) {
3717   return state_names[s];
3718 }
3719 
3720 void InstanceKlass::print_on(outputStream* st) const {
3721   assert(is_klass(), "must be klass");
3722   Klass::print_on(st);
3723 
3724   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3725   st->print(BULLET"klass size:        %d", size());                               st->cr();
3726   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
3727   st->print(BULLET"flags:             "); _misc_flags.print_on(st);               st->cr();
3728   st->print(BULLET"state:             "); st->print_cr("%s", init_state_name());
3729   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3730   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3731   st->print(BULLET"sub:               ");
3732   Klass* sub = subklass();
3733   int n;
3734   for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3735     if (n < MaxSubklassPrintSize) {
3736       sub->print_value_on(st);
3737       st->print("   ");
3738     }
3739   }

4034         nullptr;
4035       // caller can be null, for example, during a JVMTI VM_Init hook
4036       if (caller != nullptr) {
4037         info_stream.print(" source: instance of %s", caller->external_name());
4038       } else {
4039         // source is unknown
4040       }
4041     } else {
4042       oop class_loader = loader_data->class_loader();
4043       info_stream.print(" source: %s", class_loader->klass()->external_name());
4044     }
4045   } else {
4046     assert(this->in_aot_cache(), "must be");
4047     if (AOTMetaspace::in_aot_cache_dynamic_region((void*)this)) {
4048       info_stream.print(" source: shared objects file (top)");
4049     } else {
4050       info_stream.print(" source: shared objects file");
4051     }
4052   }
4053 
4054   info_stream.print(" loader:");
4055 #if INCLUDE_CDS
4056   if (in_aot_cache()) {
4057     info_stream.print(" %s", SystemDictionaryShared::loader_type_for_shared_class((Klass*)this));
4058   } else
4059 #endif
4060   if (loader_data == ClassLoaderData::the_null_class_loader_data()) {
4061     info_stream.print(" boot_loader");
4062   } else {
4063     oop class_loader = loader_data->class_loader();
4064     if (class_loader != nullptr) {
4065       info_stream.print(" %s", class_loader->klass()->external_name());
4066       oop cl_name_and_id = java_lang_ClassLoader::nameAndId(class_loader);
4067       if (cl_name_and_id != nullptr) {
4068         info_stream.print(" %s", java_lang_String::as_utf8_string(cl_name_and_id));
4069       }
4070     } else {
4071       info_stream.print(" null");
4072     }
4073   }
4074   msg.info("%s", info_stream.as_string());
4075 
4076   if (log_is_enabled(Debug, class, load)) {
4077     stringStream debug_stream;
4078 
4079     // Class hierarchy info
4080     debug_stream.print(" klass: " PTR_FORMAT " super: " PTR_FORMAT,
4081                        p2i(this),  p2i(super()));
4082 
4083     // Interfaces
4084     if (local_interfaces() != nullptr && local_interfaces()->length() > 0) {
4085       debug_stream.print(" interfaces:");
4086       int length = local_interfaces()->length();
4087       for (int i = 0; i < length; i++) {
4088         debug_stream.print(" " PTR_FORMAT,
4089                            p2i(local_interfaces()->at(i)));
4090       }
4091     }
4092 
4093     // Class loader
< prev index next >