< 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 

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


1581   Klass* k = java_lang_Class::as_Klass(java_class);
1582   if (k == nullptr) {
1583     ResourceMark rm(THREAD);
1584     THROW_(vmSymbols::java_lang_InstantiationException(), nullptr);
1585   }
1586   InstanceKlass* ik = cast(k);
1587   ik->check_valid_for_instantiation(false, CHECK_NULL);
1588   ik->initialize(CHECK_NULL);
1589   return ik->allocate_instance(THREAD);
1590 }
1591 
1592 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1593   return instanceHandle(THREAD, allocate_instance(THREAD));
1594 }
1595 
1596 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1597   if (is_interface() || is_abstract()) {
1598     ResourceMark rm(THREAD);
1599     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1600               : vmSymbols::java_lang_InstantiationException(), external_name());

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






















































1683   LogTarget(Info, class, init) lt;
1684   if (lt.is_enabled()) {
1685     ResourceMark rm(THREAD);
1686     LogStream ls(lt);
1687     ls.print("%d Initializing ", call_class_initializer_counter++);
1688     name()->print_value_on(&ls);
1689     ls.print_cr("%s (" PTR_FORMAT ") by thread \"%s\"",
1690                 h_method() == nullptr ? "(no method)" : "", p2i(this),
1691                 THREAD->name());
1692   }
1693   if (h_method() != nullptr) {
1694     ThreadInClassInitializer ticl(THREAD, this); // Track class being initialized
1695     JavaCallArguments args; // No arguments
1696     JavaValue result(T_VOID);
1697     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1698   }

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

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

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

3614 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3615   for (int i = 0; i < len; i++) {
3616     intptr_t e = start[i];
3617     st->print("%d : " INTPTR_FORMAT, i, e);
3618     if (MetaspaceObj::is_valid((Metadata*)e)) {
3619       st->print(" ");
3620       ((Metadata*)e)->print_value_on(st);
3621     }
3622     st->cr();
3623   }
3624 }
3625 
3626 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3627   return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3628 }
3629 
3630 const char* InstanceKlass::init_state_name() const {
3631   return state_names[init_state()];
3632 }
3633 




3634 void InstanceKlass::print_on(outputStream* st) const {
3635   assert(is_klass(), "must be klass");
3636   Klass::print_on(st);
3637 
3638   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3639   st->print(BULLET"klass size:        %d", size());                               st->cr();
3640   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
3641   st->print(BULLET"flags:             "); _misc_flags.print_on(st);               st->cr();
3642   st->print(BULLET"state:             "); st->print_cr("%s", init_state_name());
3643   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3644   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3645   st->print(BULLET"sub:               ");
3646   Klass* sub = subklass();
3647   int n;
3648   for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3649     if (n < MaxSubklassPrintSize) {
3650       sub->print_value_on(st);
3651       st->print("   ");
3652     }
3653   }

3948         nullptr;
3949       // caller can be null, for example, during a JVMTI VM_Init hook
3950       if (caller != nullptr) {
3951         info_stream.print(" source: instance of %s", caller->external_name());
3952       } else {
3953         // source is unknown
3954       }
3955     } else {
3956       oop class_loader = loader_data->class_loader();
3957       info_stream.print(" source: %s", class_loader->klass()->external_name());
3958     }
3959   } else {
3960     assert(this->in_aot_cache(), "must be");
3961     if (AOTMetaspace::in_aot_cache_dynamic_region((void*)this)) {
3962       info_stream.print(" source: shared objects file (top)");
3963     } else {
3964       info_stream.print(" source: shared objects file");
3965     }
3966   }
3967 




















3968   msg.info("%s", info_stream.as_string());
3969 
3970   if (log_is_enabled(Debug, class, load)) {
3971     stringStream debug_stream;
3972 
3973     // Class hierarchy info
3974     debug_stream.print(" klass: " PTR_FORMAT " super: " PTR_FORMAT,
3975                        p2i(this),  p2i(super()));
3976 
3977     // Interfaces
3978     if (local_interfaces() != nullptr && local_interfaces()->length() > 0) {
3979       debug_stream.print(" interfaces:");
3980       int length = local_interfaces()->length();
3981       for (int i = 0; i < length; i++) {
3982         debug_stream.print(" " PTR_FORMAT,
3983                            p2i(local_interfaces()->at(i)));
3984       }
3985     }
3986 
3987     // 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 

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());

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

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

2700     for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2701       if (ioe->interface_klass() != nullptr) {
2702         it->push(ioe->interface_klass_addr());
2703         itableMethodEntry* ime = ioe->first_method_entry(this);
2704         int n = klassItable::method_count_for_interface(ioe->interface_klass());
2705         for (int index = 0; index < n; index ++) {
2706           it->push(ime[index].method_addr());
2707         }
2708       }
2709     }
2710   }
2711 
2712   it->push(&_nest_host);
2713   it->push(&_nest_members);
2714   it->push(&_permitted_subclasses);
2715   it->push(&_record_components);
2716 }
2717 
2718 #if INCLUDE_CDS
2719 void InstanceKlass::remove_unshareable_info() {

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

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

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