< prev index next >

src/hotspot/share/oops/instanceKlass.cpp

Print this page

   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/archiveUtils.hpp"
  27 #include "cds/cdsConfig.hpp"

  28 #include "cds/classListWriter.hpp"
  29 #include "cds/heapShared.hpp"
  30 #include "cds/metaspaceShared.hpp"
  31 #include "classfile/classFileParser.hpp"
  32 #include "classfile/classFileStream.hpp"
  33 #include "classfile/classLoader.hpp"
  34 #include "classfile/classLoaderData.inline.hpp"
  35 #include "classfile/javaClasses.hpp"
  36 #include "classfile/moduleEntry.hpp"
  37 #include "classfile/systemDictionary.hpp"
  38 #include "classfile/systemDictionaryShared.hpp"
  39 #include "classfile/verifier.hpp"
  40 #include "classfile/vmClasses.hpp"
  41 #include "classfile/vmSymbols.hpp"
  42 #include "code/codeCache.hpp"
  43 #include "code/dependencyContext.hpp"
  44 #include "compiler/compilationPolicy.hpp"
  45 #include "compiler/compileBroker.hpp"
  46 #include "gc/shared/collectedHeap.inline.hpp"

  47 #include "interpreter/bytecodeStream.hpp"
  48 #include "interpreter/oopMapCache.hpp"
  49 #include "interpreter/rewriter.hpp"
  50 #include "jvm.h"
  51 #include "jvmtifiles/jvmti.h"
  52 #include "logging/log.hpp"
  53 #include "logging/logMessage.hpp"
  54 #include "logging/logStream.hpp"
  55 #include "memory/allocation.inline.hpp"
  56 #include "memory/iterator.inline.hpp"
  57 #include "memory/metadataFactory.hpp"
  58 #include "memory/metaspaceClosure.hpp"
  59 #include "memory/oopFactory.hpp"
  60 #include "memory/resourceArea.hpp"
  61 #include "memory/universe.hpp"
  62 #include "oops/fieldStreams.inline.hpp"
  63 #include "oops/constantPool.hpp"
  64 #include "oops/instanceClassLoaderKlass.hpp"
  65 #include "oops/instanceKlass.inline.hpp"
  66 #include "oops/instanceMirrorKlass.hpp"
  67 #include "oops/instanceOop.hpp"
  68 #include "oops/instanceStackChunkKlass.hpp"
  69 #include "oops/klass.inline.hpp"
  70 #include "oops/method.hpp"
  71 #include "oops/oop.inline.hpp"
  72 #include "oops/recordComponent.hpp"
  73 #include "oops/symbol.hpp"

  74 #include "prims/jvmtiExport.hpp"
  75 #include "prims/jvmtiRedefineClasses.hpp"
  76 #include "prims/jvmtiThreadState.hpp"
  77 #include "prims/methodComparator.hpp"
  78 #include "runtime/arguments.hpp"
  79 #include "runtime/deoptimization.hpp"
  80 #include "runtime/atomic.hpp"
  81 #include "runtime/fieldDescriptor.inline.hpp"
  82 #include "runtime/handles.inline.hpp"
  83 #include "runtime/javaCalls.hpp"
  84 #include "runtime/javaThread.inline.hpp"
  85 #include "runtime/mutexLocker.hpp"
  86 #include "runtime/orderAccess.hpp"
  87 #include "runtime/os.inline.hpp"
  88 #include "runtime/reflection.hpp"
  89 #include "runtime/threads.hpp"
  90 #include "services/classLoadingService.hpp"
  91 #include "services/finalizerService.hpp"
  92 #include "services/threadService.hpp"
  93 #include "utilities/dtrace.hpp"

 742 
 743 objArrayOop InstanceKlass::signers() const {
 744   // return the signers from the mirror
 745   return java_lang_Class::signers(java_mirror());
 746 }
 747 
 748 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
 749 // process. The step comments refers to the procedure described in that section.
 750 // Note: implementation moved to static method to expose the this pointer.
 751 void InstanceKlass::initialize(TRAPS) {
 752   if (this->should_be_initialized()) {
 753     initialize_impl(CHECK);
 754     // Note: at this point the class may be initialized
 755     //       OR it may be in the state of being initialized
 756     //       in case of recursive initialization!
 757   } else {
 758     assert(is_initialized(), "sanity check");
 759   }
 760 }
 761 



























































































 762 
 763 bool InstanceKlass::verify_code(TRAPS) {
 764   // 1) Verify the bytecodes
 765   return Verifier::verify(this, should_verify_class(), THREAD);
 766 }
 767 
 768 void InstanceKlass::link_class(TRAPS) {
 769   assert(is_loaded(), "must be loaded");
 770   if (!is_linked()) {
 771     link_class_impl(CHECK);
 772   }
 773 }
 774 
 775 void InstanceKlass::check_link_state_and_wait(JavaThread* current) {
 776   MonitorLocker ml(current, _init_monitor);
 777 
 778   bool debug_logging_enabled = log_is_enabled(Debug, class, init);
 779 
 780   // Another thread is linking this class, wait.
 781   while (is_being_linked() && !is_init_thread(current)) {

 961   return true;
 962 }
 963 
 964 // Rewrite the byte codes of all of the methods of a class.
 965 // The rewriter must be called exactly once. Rewriting must happen after
 966 // verification but before the first method of the class is executed.
 967 void InstanceKlass::rewrite_class(TRAPS) {
 968   assert(is_loaded(), "must be loaded");
 969   if (is_rewritten()) {
 970     assert(is_shared(), "rewriting an unshared class?");
 971     return;
 972   }
 973   Rewriter::rewrite(this, CHECK);
 974   set_rewritten();
 975 }
 976 
 977 // Now relocate and link method entry points after class is rewritten.
 978 // This is outside is_rewritten flag. In case of an exception, it can be
 979 // executed more than once.
 980 void InstanceKlass::link_methods(TRAPS) {


 981   int len = methods()->length();
 982   for (int i = len-1; i >= 0; i--) {
 983     methodHandle m(THREAD, methods()->at(i));
 984 
 985     // Set up method entry points for compiler and interpreter    .
 986     m->link_method(m, CHECK);
 987   }
 988 }
 989 
 990 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
 991 void InstanceKlass::initialize_super_interfaces(TRAPS) {
 992   assert (has_nonstatic_concrete_methods(), "caller should have checked this");
 993   for (int i = 0; i < local_interfaces()->length(); ++i) {
 994     InstanceKlass* ik = local_interfaces()->at(i);
 995 
 996     // Initialization is depth first search ie. we start with top of the inheritance tree
 997     // has_nonstatic_concrete_methods drives searching superinterfaces since it
 998     // means has_nonstatic_concrete_methods in its superinterface hierarchy
 999     if (ik->has_nonstatic_concrete_methods()) {
1000       ik->initialize_super_interfaces(CHECK);

1069   InitErrorTableCleaner cleaner;
1070   if (_initialization_error_table != nullptr) {
1071     _initialization_error_table->unlink(&cleaner);
1072   }
1073 }
1074 
1075 void InstanceKlass::initialize_impl(TRAPS) {
1076   HandleMark hm(THREAD);
1077 
1078   // Make sure klass is linked (verified) before initialization
1079   // A class could already be verified, since it has been reflected upon.
1080   link_class(CHECK);
1081 
1082   DTRACE_CLASSINIT_PROBE(required, -1);
1083 
1084   bool wait = false;
1085   bool throw_error = false;
1086 
1087   JavaThread* jt = THREAD;
1088 















1089   bool debug_logging_enabled = log_is_enabled(Debug, class, init);
1090 
1091   // refer to the JVM book page 47 for description of steps
1092   // Step 1
1093   {
1094     MonitorLocker ml(jt, _init_monitor);
1095 
1096     // Step 2
1097     while (is_being_initialized() && !is_init_thread(jt)) {
1098       if (debug_logging_enabled) {
1099         ResourceMark rm(jt);
1100         log_debug(class, init)("Thread \"%s\" waiting for initialization of %s by thread \"%s\"",
1101                                jt->name(), external_name(), init_thread_name());
1102       }
1103 
1104       wait = true;
1105       jt->set_class_to_be_initialized(this);
1106       ml.wait();
1107       jt->set_class_to_be_initialized(nullptr);
1108     }

1208       PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1209                                ClassLoader::perf_class_init_selftime(),
1210                                ClassLoader::perf_classes_inited(),
1211                                jt->get_thread_stat()->perf_recursion_counts_addr(),
1212                                jt->get_thread_stat()->perf_timers_addr(),
1213                                PerfClassTraceTime::CLASS_CLINIT);
1214       call_class_initializer(THREAD);
1215     } else {
1216       // The elapsed time is so small it's not worth counting.
1217       if (UsePerfData) {
1218         ClassLoader::perf_classes_inited()->inc();
1219       }
1220       call_class_initializer(THREAD);
1221     }
1222   }
1223 
1224   // Step 9
1225   if (!HAS_PENDING_EXCEPTION) {
1226     set_initialization_state_and_notify(fully_initialized, THREAD);
1227     debug_only(vtable().verify(tty, true);)

1228   }
1229   else {
1230     // Step 10 and 11
1231     Handle e(THREAD, PENDING_EXCEPTION);
1232     CLEAR_PENDING_EXCEPTION;
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       EXCEPTION_MARK;
1238       add_initialization_error(THREAD, e);
1239       set_initialization_state_and_notify(initialization_error, THREAD);
1240       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
1241       // JVMTI has already reported the pending exception
1242       // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1243       JvmtiExport::clear_detected_exception(jt);
1244     }
1245     DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1246     if (e->is_a(vmClasses::Error_klass())) {
1247       THROW_OOP(e());
1248     } else {
1249       JavaCallArguments args(e);
1250       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
1251                 vmSymbols::throwable_void_signature(),
1252                 &args);
1253     }
1254   }
1255   DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1256 }
1257 
1258 
1259 void InstanceKlass::set_initialization_state_and_notify(ClassState state, JavaThread* current) {
1260   MonitorLocker ml(current, _init_monitor);
1261 
1262   if (state == linked && UseVtableBasedCHA && Universe::is_fully_initialized()) {
1263     DeoptimizationScope deopt_scope;
1264     {
1265       // Now mark all code that assumes the class is not linked.
1266       // Set state under the Compile_lock also.
1267       MutexLocker ml(current, Compile_lock);
1268 
1269       set_init_thread(nullptr); // reset _init_thread before changing _init_state
1270       set_init_state(state);
1271 
1272       CodeCache::mark_dependents_on(&deopt_scope, this);
1273     }
1274     // Perform the deopt handshake outside Compile_lock.
1275     deopt_scope.deoptimize_marked();
1276   } else {
1277     set_init_thread(nullptr); // reset _init_thread before changing _init_state
1278     set_init_state(state);

1497     tty->print("Registered ");
1498     i->print_value_on(tty);
1499     tty->print_cr(" (" PTR_FORMAT ") as finalizable", p2i(i));
1500   }
1501   instanceHandle h_i(THREAD, i);
1502   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1503   JavaValue result(T_VOID);
1504   JavaCallArguments args(h_i);
1505   methodHandle mh(THREAD, Universe::finalizer_register_method());
1506   JavaCalls::call(&result, mh, &args, CHECK_NULL);
1507   MANAGEMENT_ONLY(FinalizerService::on_register(h_i(), THREAD);)
1508   return h_i();
1509 }
1510 
1511 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1512   assert(!is_abstract() && !is_interface(), "Should not create this object");
1513   size_t size = size_helper();  // Query before forming handle.
1514   return (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);
1515 }
1516 
1517 instanceOop InstanceKlass::allocate_instance(oop java_class, TRAPS) {


1518   Klass* k = java_lang_Class::as_Klass(java_class);
1519   if (k == nullptr) {
1520     ResourceMark rm(THREAD);
1521     THROW_(vmSymbols::java_lang_InstantiationException(), nullptr);
1522   }
1523   InstanceKlass* ik = cast(k);
1524   ik->check_valid_for_instantiation(false, CHECK_NULL);
1525   ik->initialize(CHECK_NULL);
1526   return ik->allocate_instance(THREAD);
1527 }
1528 
1529 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1530   return instanceHandle(THREAD, allocate_instance(THREAD));
1531 }
1532 
1533 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1534   if (is_interface() || is_abstract()) {
1535     ResourceMark rm(THREAD);
1536     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1537               : vmSymbols::java_lang_InstantiationException(), external_name());

1565 }
1566 
1567 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1568   // Need load-acquire for lock-free read
1569   ObjArrayKlass* oak = array_klasses_acquire();
1570   if (oak == nullptr) {
1571     return nullptr;
1572   } else {
1573     return oak->array_klass_or_null(n);
1574   }
1575 }
1576 
1577 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1578   return array_klass(1, THREAD);
1579 }
1580 
1581 ArrayKlass* InstanceKlass::array_klass_or_null() {
1582   return array_klass_or_null(1);
1583 }
1584 
1585 static int call_class_initializer_counter = 0;   // for debugging
1586 
1587 Method* InstanceKlass::class_initializer() const {
1588   Method* clinit = find_method(
1589       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1590   if (clinit != nullptr && clinit->has_valid_initializer_flags()) {
1591     return clinit;
1592   }
1593   return nullptr;
1594 }
1595 
1596 void InstanceKlass::call_class_initializer(TRAPS) {
1597   if (ReplayCompiles &&
1598       (ReplaySuppressInitializers == 1 ||
1599        (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1600     // Hide the existence of the initializer for the purpose of replaying the compile
1601     return;
1602   }
1603 
1604 #if INCLUDE_CDS
1605   // This is needed to ensure the consistency of the archived heap objects.
1606   if (has_archived_enum_objs()) {
1607     assert(is_shared(), "must be");
1608     bool initialized = HeapShared::initialize_enum_klass(this, CHECK);
1609     if (initialized) {
1610       return;
1611     }



1612   }
1613 #endif
1614 
1615   methodHandle h_method(THREAD, class_initializer());
1616   assert(!is_initialized(), "we cannot initialize twice");








































1617   LogTarget(Info, class, init) lt;
1618   if (lt.is_enabled()) {
1619     ResourceMark rm(THREAD);
1620     LogStream ls(lt);
1621     ls.print("%d Initializing ", call_class_initializer_counter++);
1622     name()->print_value_on(&ls);
1623     ls.print_cr("%s (" PTR_FORMAT ") by thread \"%s\"",
1624                 h_method() == nullptr ? "(no method)" : "", p2i(this),
1625                 THREAD->name());
1626   }
1627   if (h_method() != nullptr) {
1628     JavaCallArguments args; // No arguments
1629     JavaValue result(T_VOID);
1630     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1631   }
1632 }
1633 
1634 
1635 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1636   InterpreterOopMap* entry_for) {
1637   // Lazily create the _oop_map_cache at first request.
1638   // Load_acquire is needed to safely get instance published with CAS by another thread.
1639   OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache);
1640   if (oop_map_cache == nullptr) {
1641     // Try to install new instance atomically.
1642     oop_map_cache = new OopMapCache();
1643     OopMapCache* other = Atomic::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
1644     if (other != nullptr) {
1645       // Someone else managed to install before us, ditch local copy and use the existing one.
1646       delete oop_map_cache;
1647       oop_map_cache = other;
1648     }
1649   }
1650   // _oop_map_cache is constant after init; lookup below does its own locking.
1651   oop_map_cache->lookup(method, bci, entry_for);
1652 }
1653 
1654 bool InstanceKlass::contains_field_offset(int offset) {

2375     }
2376   }
2377   if (new_jmeths != 0) {
2378     Method::ensure_jmethod_ids(class_loader_data(), new_jmeths);
2379   }
2380 }
2381 
2382 // Lookup a jmethodID, null if not found.  Do no blocking, no allocations, no handles
2383 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
2384   int idnum = method->method_idnum();
2385   jmethodID* jmeths = methods_jmethod_ids_acquire();
2386   return (jmeths != nullptr) ? jmeths[idnum + 1] : nullptr;
2387 }
2388 
2389 inline DependencyContext InstanceKlass::dependencies() {
2390   DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);
2391   return dep_context;
2392 }
2393 
2394 void InstanceKlass::mark_dependent_nmethods(DeoptimizationScope* deopt_scope, KlassDepChange& changes) {
2395   dependencies().mark_dependent_nmethods(deopt_scope, changes);
2396 }
2397 
2398 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2399   dependencies().add_dependent_nmethod(nm);
2400 }
2401 
2402 void InstanceKlass::clean_dependency_context() {
2403   dependencies().clean_unloading_dependents();
2404 }
2405 
2406 #ifndef PRODUCT
2407 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2408   dependencies().print_dependent_nmethods(verbose);
2409 }
2410 
2411 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2412   return dependencies().is_dependent_nmethod(nm);
2413 }
2414 #endif //PRODUCT
2415 

2504   if (itable_length() > 0) {
2505     itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2506     int method_table_offset_in_words = ioe->offset()/wordSize;
2507     int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2508 
2509     int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2510                          / itableOffsetEntry::size();
2511 
2512     for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2513       if (ioe->interface_klass() != nullptr) {
2514         it->push(ioe->interface_klass_addr());
2515         itableMethodEntry* ime = ioe->first_method_entry(this);
2516         int n = klassItable::method_count_for_interface(ioe->interface_klass());
2517         for (int index = 0; index < n; index ++) {
2518           it->push(ime[index].method_addr());
2519         }
2520       }
2521     }
2522   }
2523 

2524   it->push(&_nest_members);
2525   it->push(&_permitted_subclasses);
2526   it->push(&_record_components);
2527 }
2528 
2529 #if INCLUDE_CDS
2530 void InstanceKlass::remove_unshareable_info() {
2531 
2532   if (is_linked()) {
2533     assert(can_be_verified_at_dumptime(), "must be");
2534     // Remember this so we can avoid walking the hierarchy at runtime.
2535     set_verified_at_dump_time();
2536   }

2537 
2538   Klass::remove_unshareable_info();
2539 
2540   if (SystemDictionaryShared::has_class_failed_verification(this)) {
2541     // Classes are attempted to link during dumping and may fail,
2542     // but these classes are still in the dictionary and class list in CLD.
2543     // If the class has failed verification, there is nothing else to remove.
2544     return;
2545   }
2546 
2547   // Reset to the 'allocated' state to prevent any premature accessing to
2548   // a shared class at runtime while the class is still being loaded and
2549   // restored. A class' init_state is set to 'loaded' at runtime when it's
2550   // being added to class hierarchy (see InstanceKlass:::add_to_hierarchy()).
2551   _init_state = allocated;
2552 
2553   { // Otherwise this needs to take out the Compile_lock.
2554     assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2555     init_implementor();
2556   }
2557 
2558   constants()->remove_unshareable_info();

2559 
2560   for (int i = 0; i < methods()->length(); i++) {
2561     Method* m = methods()->at(i);
2562     m->remove_unshareable_info();
2563   }
2564 
2565   // do array classes also.
2566   if (array_klasses() != nullptr) {
2567     array_klasses()->remove_unshareable_info();
2568   }
2569 
2570   // These are not allocated from metaspace. They are safe to set to null.
2571   _source_debug_extension = nullptr;
2572   _dep_context = nullptr;
2573   _osr_nmethods_head = nullptr;
2574 #if INCLUDE_JVMTI
2575   _breakpoints = nullptr;
2576   _previous_versions = nullptr;
2577   _cached_class_file = nullptr;
2578   _jvmti_cached_class_field_map = nullptr;
2579 #endif
2580 
2581   _init_thread = nullptr;
2582   _methods_jmethod_ids = nullptr;
2583   _jni_ids = nullptr;
2584   _oop_map_cache = nullptr;
2585   // clear _nest_host to ensure re-load at runtime
2586   _nest_host = nullptr;




2587   init_shared_package_entry();
2588   _dep_context_last_cleaned = 0;
2589   _init_monitor = nullptr;

2590 
2591   remove_unshareable_flags();
2592 }
2593 
2594 void InstanceKlass::remove_unshareable_flags() {
2595   // clear all the flags/stats that shouldn't be in the archived version
2596   assert(!is_scratch_class(), "must be");
2597   assert(!has_been_redefined(), "must be");
2598 #if INCLUDE_JVMTI
2599   set_is_being_redefined(false);
2600 #endif
2601   set_has_resolved_methods(false);
2602 }
2603 
2604 void InstanceKlass::remove_java_mirror() {
2605   Klass::remove_java_mirror();
2606 
2607   // do array classes also.
2608   if (array_klasses() != nullptr) {
2609     array_klasses()->remove_java_mirror();

2678 
2679   if (array_klasses() != nullptr) {
2680     // To get a consistent list of classes we need MultiArray_lock to ensure
2681     // array classes aren't observed while they are being restored.
2682     RecursiveLocker rl(MultiArray_lock, THREAD);
2683     assert(this == array_klasses()->bottom_klass(), "sanity");
2684     // Array classes have null protection domain.
2685     // --> see ArrayKlass::complete_create_array_klass()
2686     array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
2687   }
2688 
2689   // Initialize @ValueBased class annotation
2690   if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation()) {
2691     set_is_value_based();
2692   }
2693 
2694   // restore the monitor
2695   _init_monitor = create_init_monitor("InstanceKlassInitMonitorRestored_lock");
2696 }
2697 
2698 // Check if a class or any of its supertypes has a version older than 50.
2699 // CDS will not perform verification of old classes during dump time because
2700 // without changing the old verifier, the verification constraint cannot be
2701 // retrieved during dump time.
2702 // Verification of archived old classes will be performed during run time.
2703 bool InstanceKlass::can_be_verified_at_dumptime() const {




2704   if (MetaspaceShared::is_in_shared_metaspace(this)) {
2705     // This is a class that was dumped into the base archive, so we know
2706     // it was verified at dump time.
2707     return true;
2708   }











2709   if (major_version() < 50 /*JAVA_6_VERSION*/) {
2710     return false;
2711   }
2712   if (java_super() != nullptr && !java_super()->can_be_verified_at_dumptime()) {
2713     return false;
2714   }
2715   Array<InstanceKlass*>* interfaces = local_interfaces();
2716   int len = interfaces->length();
2717   for (int i = 0; i < len; i++) {
2718     if (!interfaces->at(i)->can_be_verified_at_dumptime()) {
2719       return false;
2720     }
2721   }
2722   return true;
2723 }
2724 
2725 bool InstanceKlass::methods_contain_jsr_bytecode() const {
2726   Thread* thread = Thread::current();
2727   for (int i = 0; i < _methods->length(); i++) {
2728     methodHandle m(thread, _methods->at(i));
2729     BytecodeStream bcs(m);
2730     while (!bcs.is_last_bytecode()) {
2731       Bytecodes::Code opcode = bcs.next();
2732       if (opcode == Bytecodes::_jsr || opcode == Bytecodes::_jsr_w) {
2733         return true;
2734       }
2735     }
2736   }
2737   return false;
2738 }












2739 #endif // INCLUDE_CDS
2740 
2741 #if INCLUDE_JVMTI
2742 static void clear_all_breakpoints(Method* m) {
2743   m->clear_all_breakpoints();
2744 }
2745 #endif
2746 
2747 void InstanceKlass::unload_class(InstanceKlass* ik) {
2748   // Release dependencies.
2749   ik->dependencies().remove_all_dependents();
2750 
2751   // notify the debugger
2752   if (JvmtiExport::should_post_class_unload()) {
2753     JvmtiExport::post_class_unload(ik);
2754   }
2755 
2756   // notify ClassLoadingService of class unload
2757   ClassLoadingService::notify_class_unloaded(ik);
2758 

3488 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3489   for (int i = 0; i < len; i++) {
3490     intptr_t e = start[i];
3491     st->print("%d : " INTPTR_FORMAT, i, e);
3492     if (MetaspaceObj::is_valid((Metadata*)e)) {
3493       st->print(" ");
3494       ((Metadata*)e)->print_value_on(st);
3495     }
3496     st->cr();
3497   }
3498 }
3499 
3500 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3501   return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3502 }
3503 
3504 const char* InstanceKlass::init_state_name() const {
3505   return state_names[init_state()];
3506 }
3507 




3508 void InstanceKlass::print_on(outputStream* st) const {
3509   assert(is_klass(), "must be klass");
3510   Klass::print_on(st);
3511 
3512   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3513   st->print(BULLET"klass size:        %d", size());                               st->cr();
3514   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
3515   st->print(BULLET"flags:             "); _misc_flags.print_on(st);               st->cr();
3516   st->print(BULLET"state:             "); st->print_cr("%s", init_state_name());
3517   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3518   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3519   st->print(BULLET"sub:               ");
3520   Klass* sub = subklass();
3521   int n;
3522   for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3523     if (n < MaxSubklassPrintSize) {
3524       sub->print_value_on(st);
3525       st->print("   ");
3526     }
3527   }

3830         nullptr;
3831       // caller can be null, for example, during a JVMTI VM_Init hook
3832       if (caller != nullptr) {
3833         info_stream.print(" source: instance of %s", caller->external_name());
3834       } else {
3835         // source is unknown
3836       }
3837     } else {
3838       oop class_loader = loader_data->class_loader();
3839       info_stream.print(" source: %s", class_loader->klass()->external_name());
3840     }
3841   } else {
3842     assert(this->is_shared(), "must be");
3843     if (MetaspaceShared::is_shared_dynamic((void*)this)) {
3844       info_stream.print(" source: shared objects file (top)");
3845     } else {
3846       info_stream.print(" source: shared objects file");
3847     }
3848   }
3849 

















3850   msg.info("%s", info_stream.as_string());
3851 
3852   if (log_is_enabled(Debug, class, load)) {
3853     stringStream debug_stream;
3854 
3855     // Class hierarchy info
3856     debug_stream.print(" klass: " PTR_FORMAT " super: " PTR_FORMAT,
3857                        p2i(this),  p2i(superklass()));
3858 
3859     // Interfaces
3860     if (local_interfaces() != nullptr && local_interfaces()->length() > 0) {
3861       debug_stream.print(" interfaces:");
3862       int length = local_interfaces()->length();
3863       for (int i = 0; i < length; i++) {
3864         debug_stream.print(" " PTR_FORMAT,
3865                            p2i(InstanceKlass::cast(local_interfaces()->at(i))));
3866       }
3867     }
3868 
3869     // Class loader

   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/archiveUtils.hpp"
  27 #include "cds/cdsConfig.hpp"
  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/threads.hpp"
  93 #include "services/classLoadingService.hpp"
  94 #include "services/finalizerService.hpp"
  95 #include "services/threadService.hpp"
  96 #include "utilities/dtrace.hpp"

 745 
 746 objArrayOop InstanceKlass::signers() const {
 747   // return the signers from the mirror
 748   return java_lang_Class::signers(java_mirror());
 749 }
 750 
 751 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
 752 // process. The step comments refers to the procedure described in that section.
 753 // Note: implementation moved to static method to expose the this pointer.
 754 void InstanceKlass::initialize(TRAPS) {
 755   if (this->should_be_initialized()) {
 756     initialize_impl(CHECK);
 757     // Note: at this point the class may be initialized
 758     //       OR it may be in the state of being initialized
 759     //       in case of recursive initialization!
 760   } else {
 761     assert(is_initialized(), "sanity check");
 762   }
 763 }
 764 
 765 static bool are_super_types_initialized(InstanceKlass* ik) {
 766   InstanceKlass* s = ik->java_super();
 767   if (s != nullptr && !s->is_initialized()) {
 768     return false;
 769   }
 770 
 771   if (ik->has_nonstatic_concrete_methods()) {
 772     // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
 773     // having a superinterface that declares, non-static, concrete methods
 774     Array<InstanceKlass*>* interfaces = ik->local_interfaces();
 775     int len = interfaces->length();
 776     for (int i = 0; i < len; i++) {
 777       InstanceKlass* intf = interfaces->at(i);
 778       if (!intf->is_initialized()) {
 779         return false;
 780       }
 781     }
 782   }
 783 
 784   return true;
 785 }
 786 
 787 static void log_class_init_start(outputStream* st, JavaThread* current, InstanceKlass* ik, int init_id) {
 788   ResourceMark rm;
 789   const char* info = "";
 790   if (ik->has_preinitialized_mirror() && CDSConfig::is_loading_heap()) {
 791     info = " (preinitialized)";
 792   } else if (ik->class_initializer() == nullptr) {
 793     info = " (no method)";
 794   }
 795   st->print("%d Initializing ", init_id);
 796   ik->name()->print_value_on(st);
 797   st->print_cr("%s (" PTR_FORMAT ") by thread " PTR_FORMAT " \"%s\"", info, p2i(ik), p2i(current), current->name());
 798 }
 799 
 800 static int log_class_init(JavaThread* current, InstanceKlass* ik) {
 801   int init_id = -1;
 802   LogStreamHandle(Info,  init, class) lsh1;
 803   LogStreamHandle(Debug, init)        lsh2;
 804   if (lsh1.is_enabled() || lsh2.is_enabled()) {
 805     static int call_class_initializer_counter = 0;  // for debugging
 806     init_id = Atomic::fetch_then_add(&call_class_initializer_counter, 1);
 807     if (lsh1.is_enabled()) {
 808       log_class_init_start(&lsh1, current, ik, init_id);
 809     }
 810     if (lsh2.is_enabled() && ik->class_initializer() != nullptr && !ik->has_preinitialized_mirror()) {
 811       log_class_init_start(&lsh2, current, ik, init_id);
 812     }
 813   }
 814   return init_id;
 815 }
 816 
 817 void InstanceKlass::initialize_from_cds(TRAPS) {
 818   if (is_initialized()) {
 819     return;
 820   }
 821 
 822   if (has_preinitialized_mirror() && CDSConfig::is_loading_heap() &&
 823       !ForceProfiling &&
 824       !RecordTraining &&
 825       are_super_types_initialized(this)) {
 826     // FIXME: also check for events listeners such as JVMTI, JFR, etc
 827     if (log_is_enabled(Info, cds, init)) {
 828       ResourceMark rm;
 829       log_info(cds, init)("%s (quickest)", external_name());
 830     }
 831 
 832     link_class(CHECK);
 833 
 834 #ifdef AZZERT
 835     {
 836       MonitorLocker ml(THREAD, _init_monitor);
 837       assert(!initialized(), "sanity");
 838       assert(!is_being_initialized(), "sanity");
 839       assert(!is_in_error_state(), "sanity");
 840     }
 841 #endif
 842 
 843     log_class_init(THREAD, this);
 844     set_init_thread(THREAD);
 845     set_initialization_state_and_notify(fully_initialized, CHECK);
 846     return;
 847   }
 848 
 849   if (log_is_enabled(Info, cds, init)) {
 850     ResourceMark rm;
 851     log_info(cds, init)("%s%s", external_name(),
 852                         (has_preinitialized_mirror() && CDSConfig::is_loading_heap()) ? " (quicker)" : "");
 853   }
 854   initialize(THREAD);
 855 }
 856 
 857 bool InstanceKlass::verify_code(TRAPS) {
 858   // 1) Verify the bytecodes
 859   return Verifier::verify(this, should_verify_class(), THREAD);
 860 }
 861 
 862 void InstanceKlass::link_class(TRAPS) {
 863   assert(is_loaded(), "must be loaded");
 864   if (!is_linked()) {
 865     link_class_impl(CHECK);
 866   }
 867 }
 868 
 869 void InstanceKlass::check_link_state_and_wait(JavaThread* current) {
 870   MonitorLocker ml(current, _init_monitor);
 871 
 872   bool debug_logging_enabled = log_is_enabled(Debug, class, init);
 873 
 874   // Another thread is linking this class, wait.
 875   while (is_being_linked() && !is_init_thread(current)) {

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

1165   InitErrorTableCleaner cleaner;
1166   if (_initialization_error_table != nullptr) {
1167     _initialization_error_table->unlink(&cleaner);
1168   }
1169 }
1170 
1171 void InstanceKlass::initialize_impl(TRAPS) {
1172   HandleMark hm(THREAD);
1173 
1174   // Make sure klass is linked (verified) before initialization
1175   // A class could already be verified, since it has been reflected upon.
1176   link_class(CHECK);
1177 
1178   DTRACE_CLASSINIT_PROBE(required, -1);
1179 
1180   bool wait = false;
1181   bool throw_error = false;
1182 
1183   JavaThread* jt = THREAD;
1184 
1185   if (ForceProfiling) {
1186     // Preallocate MDOs.
1187     for (int i = 0; i < methods()->length(); i++) {
1188       assert(!HAS_PENDING_EXCEPTION, "");
1189       methodHandle m(THREAD, methods()->at(i));
1190       Method::build_profiling_method_data(m, THREAD);
1191       if (HAS_PENDING_EXCEPTION) {
1192         ResourceMark rm;
1193         log_warning(cds)("MDO preallocation failed for %s", external_name());
1194         CLEAR_PENDING_EXCEPTION;
1195         break;
1196       }
1197     }
1198   }
1199 
1200   bool debug_logging_enabled = log_is_enabled(Debug, class, init);
1201 
1202   // refer to the JVM book page 47 for description of steps
1203   // Step 1
1204   {
1205     MonitorLocker ml(jt, _init_monitor);
1206 
1207     // Step 2
1208     while (is_being_initialized() && !is_init_thread(jt)) {
1209       if (debug_logging_enabled) {
1210         ResourceMark rm(jt);
1211         log_debug(class, init)("Thread \"%s\" waiting for initialization of %s by thread \"%s\"",
1212                                jt->name(), external_name(), init_thread_name());
1213       }
1214 
1215       wait = true;
1216       jt->set_class_to_be_initialized(this);
1217       ml.wait();
1218       jt->set_class_to_be_initialized(nullptr);
1219     }

1319       PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1320                                ClassLoader::perf_class_init_selftime(),
1321                                ClassLoader::perf_classes_inited(),
1322                                jt->get_thread_stat()->perf_recursion_counts_addr(),
1323                                jt->get_thread_stat()->perf_timers_addr(),
1324                                PerfClassTraceTime::CLASS_CLINIT);
1325       call_class_initializer(THREAD);
1326     } else {
1327       // The elapsed time is so small it's not worth counting.
1328       if (UsePerfData) {
1329         ClassLoader::perf_classes_inited()->inc();
1330       }
1331       call_class_initializer(THREAD);
1332     }
1333   }
1334 
1335   // Step 9
1336   if (!HAS_PENDING_EXCEPTION) {
1337     set_initialization_state_and_notify(fully_initialized, THREAD);
1338     debug_only(vtable().verify(tty, true);)
1339     CompilationPolicy::replay_training_at_init(this, THREAD);
1340   }
1341   else {
1342     // Step 10 and 11
1343     Handle e(THREAD, PENDING_EXCEPTION);
1344     CLEAR_PENDING_EXCEPTION;
1345     // JVMTI has already reported the pending exception
1346     // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1347     JvmtiExport::clear_detected_exception(jt);
1348     {
1349       EXCEPTION_MARK;
1350       add_initialization_error(THREAD, e);
1351       set_initialization_state_and_notify(initialization_error, THREAD);
1352       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
1353       // JVMTI has already reported the pending exception
1354       // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1355       JvmtiExport::clear_detected_exception(jt);
1356     }
1357     DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1358     if (e->is_a(vmClasses::Error_klass())) {
1359       THROW_OOP(e());
1360     } else {
1361       JavaCallArguments args(e);
1362       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
1363                 vmSymbols::throwable_void_signature(),
1364                 &args);
1365     }
1366   }
1367   DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1368 }
1369 

1370 void InstanceKlass::set_initialization_state_and_notify(ClassState state, JavaThread* current) {
1371   MonitorLocker ml(current, _init_monitor);
1372 
1373   if (state == linked && UseVtableBasedCHA && Universe::is_fully_initialized()) {
1374     DeoptimizationScope deopt_scope;
1375     {
1376       // Now mark all code that assumes the class is not linked.
1377       // Set state under the Compile_lock also.
1378       MutexLocker ml(current, Compile_lock);
1379 
1380       set_init_thread(nullptr); // reset _init_thread before changing _init_state
1381       set_init_state(state);
1382 
1383       CodeCache::mark_dependents_on(&deopt_scope, this);
1384     }
1385     // Perform the deopt handshake outside Compile_lock.
1386     deopt_scope.deoptimize_marked();
1387   } else {
1388     set_init_thread(nullptr); // reset _init_thread before changing _init_state
1389     set_init_state(state);

1608     tty->print("Registered ");
1609     i->print_value_on(tty);
1610     tty->print_cr(" (" PTR_FORMAT ") as finalizable", p2i(i));
1611   }
1612   instanceHandle h_i(THREAD, i);
1613   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1614   JavaValue result(T_VOID);
1615   JavaCallArguments args(h_i);
1616   methodHandle mh(THREAD, Universe::finalizer_register_method());
1617   JavaCalls::call(&result, mh, &args, CHECK_NULL);
1618   MANAGEMENT_ONLY(FinalizerService::on_register(h_i(), THREAD);)
1619   return h_i();
1620 }
1621 
1622 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1623   assert(!is_abstract() && !is_interface(), "Should not create this object");
1624   size_t size = size_helper();  // Query before forming handle.
1625   return (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);
1626 }
1627 
1628 instanceOop InstanceKlass::allocate_instance(oop java_class,
1629                                              const char* who,
1630                                              TRAPS) {
1631   Klass* k = java_lang_Class::as_Klass(java_class);
1632   if (k == nullptr) {
1633     ResourceMark rm(THREAD);
1634     THROW_(vmSymbols::java_lang_InstantiationException(), nullptr);
1635   }
1636   InstanceKlass* ik = cast(k);
1637   ik->check_valid_for_instantiation(false, CHECK_NULL);
1638   ik->initialize(CHECK_NULL);
1639   return ik->allocate_instance(THREAD);
1640 }
1641 
1642 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1643   return instanceHandle(THREAD, allocate_instance(THREAD));
1644 }
1645 
1646 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1647   if (is_interface() || is_abstract()) {
1648     ResourceMark rm(THREAD);
1649     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1650               : vmSymbols::java_lang_InstantiationException(), external_name());

1678 }
1679 
1680 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1681   // Need load-acquire for lock-free read
1682   ObjArrayKlass* oak = array_klasses_acquire();
1683   if (oak == nullptr) {
1684     return nullptr;
1685   } else {
1686     return oak->array_klass_or_null(n);
1687   }
1688 }
1689 
1690 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1691   return array_klass(1, THREAD);
1692 }
1693 
1694 ArrayKlass* InstanceKlass::array_klass_or_null() {
1695   return array_klass_or_null(1);
1696 }
1697 


1698 Method* InstanceKlass::class_initializer() const {
1699   Method* clinit = find_method(
1700       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1701   if (clinit != nullptr && clinit->has_valid_initializer_flags()) {
1702     return clinit;
1703   }
1704   return nullptr;
1705 }
1706 
1707 void InstanceKlass::call_class_initializer(TRAPS) {
1708   if (ReplayCompiles &&
1709       (ReplaySuppressInitializers == 1 ||
1710        (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1711     // Hide the existence of the initializer for the purpose of replaying the compile
1712     return;
1713   }
1714 
1715 #if INCLUDE_CDS
1716   // This is needed to ensure the consistency of the archived heap objects.
1717   if (has_archived_enum_objs()) {
1718     assert(is_shared(), "must be");
1719     bool initialized = CDSEnumKlass::initialize_enum_klass(this, CHECK);
1720     if (initialized) {
1721       return;
1722     }
1723   } else if (has_preinitialized_mirror() && CDSConfig::is_loading_heap()) {
1724     log_class_init(THREAD, this);
1725     return;
1726   }
1727 #endif
1728 
1729   methodHandle h_method(THREAD, class_initializer());
1730   assert(!is_initialized(), "we cannot initialize twice");
1731   int init_id = log_class_init(THREAD, this);
1732   if (h_method() != nullptr) {
1733     JavaCallArguments args; // No arguments
1734     JavaValue result(T_VOID);
1735     InstanceKlass* outer = THREAD->set_class_being_initialized(this);
1736     jlong bc_start = (CountBytecodesPerThread ? THREAD->bc_counter_value() : BytecodeCounter::counter_value());
1737 
1738     elapsedTimer timer;
1739     {
1740       PerfPauseTimer pt(THREAD->current_rt_call_timer(), THREAD->profile_rt_calls());
1741       PauseRuntimeCallProfiling prcp(THREAD, THREAD->profile_rt_calls());
1742 
1743       timer.start();
1744       JavaCalls::call(&result, h_method, &args, THREAD); // Static call (no args)
1745       timer.stop();
1746     }
1747 
1748     jlong bc_end = (CountBytecodesPerThread ? THREAD->bc_counter_value() : BytecodeCounter::counter_value());
1749 
1750     jlong bc_executed = (bc_end - bc_start);
1751     if (UsePerfData && outer == nullptr) { // outermost clinit
1752       THREAD->inc_clinit_bc_counter_value(bc_executed);
1753       ClassLoader::perf_class_init_bytecodes_count()->inc(bc_executed);
1754     }
1755 
1756     THREAD->set_class_being_initialized(outer);
1757 
1758     LogStreamHandle(Debug, init) log;
1759     if (log.is_enabled()) {
1760       ResourceMark rm(THREAD);
1761       log.print("%d Initialized in %.3fms (total: %ldms); ",
1762                 init_id, timer.seconds() * 1000.0, ClassLoader::class_init_time_ms());
1763       if (CountBytecodes || CountBytecodesPerThread) {
1764         log.print("executed %ld bytecodes; ", bc_executed);
1765       }
1766       name()->print_value_on(&log);
1767       log.print_cr(" by thread " PTR_FORMAT " \"%s\" (" PTR_FORMAT ")",
1768                    p2i(THREAD), THREAD->name(), p2i(this));
1769     }
1770   }
1771   LogTarget(Info, class, init) lt;
1772   if (lt.is_enabled()) {
1773     ResourceMark rm(THREAD);
1774     LogStream ls(lt);
1775     ls.print("%d Initialized ", init_id);
1776     name()->print_value_on(&ls);
1777     ls.print_cr("%s (" PTR_FORMAT ")", h_method() == nullptr ? "(no method)" : "", p2i(this));







1778   }
1779 }
1780 

1781 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1782   InterpreterOopMap* entry_for) {
1783   // Lazily create the _oop_map_cache at first request.
1784   // Load_acquire is needed to safely get instance published with CAS by another thread.
1785   OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache);
1786   if (oop_map_cache == nullptr) {
1787     // Try to install new instance atomically.
1788     oop_map_cache = new OopMapCache();
1789     OopMapCache* other = Atomic::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
1790     if (other != nullptr) {
1791       // Someone else managed to install before us, ditch local copy and use the existing one.
1792       delete oop_map_cache;
1793       oop_map_cache = other;
1794     }
1795   }
1796   // _oop_map_cache is constant after init; lookup below does its own locking.
1797   oop_map_cache->lookup(method, bci, entry_for);
1798 }
1799 
1800 bool InstanceKlass::contains_field_offset(int offset) {

2521     }
2522   }
2523   if (new_jmeths != 0) {
2524     Method::ensure_jmethod_ids(class_loader_data(), new_jmeths);
2525   }
2526 }
2527 
2528 // Lookup a jmethodID, null if not found.  Do no blocking, no allocations, no handles
2529 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
2530   int idnum = method->method_idnum();
2531   jmethodID* jmeths = methods_jmethod_ids_acquire();
2532   return (jmeths != nullptr) ? jmeths[idnum + 1] : nullptr;
2533 }
2534 
2535 inline DependencyContext InstanceKlass::dependencies() {
2536   DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);
2537   return dep_context;
2538 }
2539 
2540 void InstanceKlass::mark_dependent_nmethods(DeoptimizationScope* deopt_scope, KlassDepChange& changes) {
2541   dependencies().mark_dependent_nmethods(deopt_scope, changes, this);
2542 }
2543 
2544 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2545   dependencies().add_dependent_nmethod(nm);
2546 }
2547 
2548 void InstanceKlass::clean_dependency_context() {
2549   dependencies().clean_unloading_dependents();
2550 }
2551 
2552 #ifndef PRODUCT
2553 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2554   dependencies().print_dependent_nmethods(verbose);
2555 }
2556 
2557 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2558   return dependencies().is_dependent_nmethod(nm);
2559 }
2560 #endif //PRODUCT
2561 

2650   if (itable_length() > 0) {
2651     itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2652     int method_table_offset_in_words = ioe->offset()/wordSize;
2653     int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2654 
2655     int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2656                          / itableOffsetEntry::size();
2657 
2658     for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2659       if (ioe->interface_klass() != nullptr) {
2660         it->push(ioe->interface_klass_addr());
2661         itableMethodEntry* ime = ioe->first_method_entry(this);
2662         int n = klassItable::method_count_for_interface(ioe->interface_klass());
2663         for (int index = 0; index < n; index ++) {
2664           it->push(ime[index].method_addr());
2665         }
2666       }
2667     }
2668   }
2669 
2670   it->push(&_nest_host);
2671   it->push(&_nest_members);
2672   it->push(&_permitted_subclasses);
2673   it->push(&_record_components);
2674 }
2675 
2676 #if INCLUDE_CDS
2677 void InstanceKlass::remove_unshareable_info() {

2678   if (is_linked()) {
2679     assert(can_be_verified_at_dumptime(), "must be");
2680     // Remember this so we can avoid walking the hierarchy at runtime.
2681     set_verified_at_dump_time();
2682   }
2683   _misc_flags.set_has_init_deps_processed(false);
2684 
2685   Klass::remove_unshareable_info();
2686 
2687   if (SystemDictionaryShared::has_class_failed_verification(this)) {
2688     // Classes are attempted to link during dumping and may fail,
2689     // but these classes are still in the dictionary and class list in CLD.
2690     // If the class has failed verification, there is nothing else to remove.
2691     return;
2692   }
2693 
2694   // Reset to the 'allocated' state to prevent any premature accessing to
2695   // a shared class at runtime while the class is still being loaded and
2696   // restored. A class' init_state is set to 'loaded' at runtime when it's
2697   // being added to class hierarchy (see InstanceKlass:::add_to_hierarchy()).
2698   _init_state = allocated;
2699 
2700   { // Otherwise this needs to take out the Compile_lock.
2701     assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2702     init_implementor();
2703   }
2704 
2705   // ConstantPool is cleaned separately. See ArchiveBuilder::make_klasses_shareable()
2706   // constants()->remove_unshareable_info();
2707 
2708   for (int i = 0; i < methods()->length(); i++) {
2709     Method* m = methods()->at(i);
2710     m->remove_unshareable_info();
2711   }
2712 
2713   // do array classes also.
2714   if (array_klasses() != nullptr) {
2715     array_klasses()->remove_unshareable_info();
2716   }
2717 
2718   // These are not allocated from metaspace. They are safe to set to null.
2719   _source_debug_extension = nullptr;
2720   _dep_context = nullptr;
2721   _osr_nmethods_head = nullptr;
2722 #if INCLUDE_JVMTI
2723   _breakpoints = nullptr;
2724   _previous_versions = nullptr;
2725   _cached_class_file = nullptr;
2726   _jvmti_cached_class_field_map = nullptr;
2727 #endif
2728 
2729   _init_thread = nullptr;
2730   _methods_jmethod_ids = nullptr;
2731   _jni_ids = nullptr;
2732   _oop_map_cache = nullptr;
2733   if (ArchiveInvokeDynamic && HeapShared::is_lambda_proxy_klass(this)) {
2734     // keep _nest_host
2735   } else {
2736     // clear _nest_host to ensure re-load at runtime
2737     _nest_host = nullptr;
2738   }
2739   init_shared_package_entry();
2740   _dep_context_last_cleaned = 0;
2741   _init_monitor = nullptr;
2742   DEBUG_ONLY(_shared_class_load_count = 0);
2743 
2744   remove_unshareable_flags();
2745 }
2746 
2747 void InstanceKlass::remove_unshareable_flags() {
2748   // clear all the flags/stats that shouldn't be in the archived version
2749   assert(!is_scratch_class(), "must be");
2750   assert(!has_been_redefined(), "must be");
2751 #if INCLUDE_JVMTI
2752   set_is_being_redefined(false);
2753 #endif
2754   set_has_resolved_methods(false);
2755 }
2756 
2757 void InstanceKlass::remove_java_mirror() {
2758   Klass::remove_java_mirror();
2759 
2760   // do array classes also.
2761   if (array_klasses() != nullptr) {
2762     array_klasses()->remove_java_mirror();

2831 
2832   if (array_klasses() != nullptr) {
2833     // To get a consistent list of classes we need MultiArray_lock to ensure
2834     // array classes aren't observed while they are being restored.
2835     RecursiveLocker rl(MultiArray_lock, THREAD);
2836     assert(this == array_klasses()->bottom_klass(), "sanity");
2837     // Array classes have null protection domain.
2838     // --> see ArrayKlass::complete_create_array_klass()
2839     array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
2840   }
2841 
2842   // Initialize @ValueBased class annotation
2843   if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation()) {
2844     set_is_value_based();
2845   }
2846 
2847   // restore the monitor
2848   _init_monitor = create_init_monitor("InstanceKlassInitMonitorRestored_lock");
2849 }
2850 





2851 bool InstanceKlass::can_be_verified_at_dumptime() const {
2852   if (CDSConfig::preserve_all_dumptime_verification_states(this)) {
2853     return true;
2854   }
2855 
2856   if (MetaspaceShared::is_in_shared_metaspace(this)) {
2857     // This is a class that was dumped into the base archive, so we know
2858     // it was verified at dump time.
2859     return true;
2860   }
2861 
2862   if (ArchiveInvokeDynamic) {
2863     // FIXME: this works around JDK-8315719
2864     return true;
2865   }
2866 
2867   // Check if a class or any of its supertypes has a version older than 50.
2868   // CDS will not perform verification of old classes during dump time because
2869   // without changing the old verifier, the verification constraint cannot be
2870   // retrieved during dump time.
2871   // Verification of archived old classes will be performed during run time.
2872   if (major_version() < 50 /*JAVA_6_VERSION*/) {
2873     return false;
2874   }
2875   if (java_super() != nullptr && !java_super()->can_be_verified_at_dumptime()) {
2876     return false;
2877   }
2878   Array<InstanceKlass*>* interfaces = local_interfaces();
2879   int len = interfaces->length();
2880   for (int i = 0; i < len; i++) {
2881     if (!interfaces->at(i)->can_be_verified_at_dumptime()) {
2882       return false;
2883     }
2884   }
2885   return true;
2886 }
2887 
2888 bool InstanceKlass::methods_contain_jsr_bytecode() const {
2889   Thread* thread = Thread::current();
2890   for (int i = 0; i < _methods->length(); i++) {
2891     methodHandle m(thread, _methods->at(i));
2892     BytecodeStream bcs(m);
2893     while (!bcs.is_last_bytecode()) {
2894       Bytecodes::Code opcode = bcs.next();
2895       if (opcode == Bytecodes::_jsr || opcode == Bytecodes::_jsr_w) {
2896         return true;
2897       }
2898     }
2899   }
2900   return false;
2901 }
2902 
2903 int InstanceKlass::shared_class_loader_type() const {
2904   if (is_shared_boot_class()) {
2905     return ClassLoader::BOOT_LOADER;
2906   } else if (is_shared_platform_class()) {
2907     return ClassLoader::PLATFORM_LOADER;
2908   } else if (is_shared_app_class()) {
2909     return ClassLoader::APP_LOADER;
2910   } else {
2911     return ClassLoader::OTHER;
2912   }
2913 }
2914 #endif // INCLUDE_CDS
2915 
2916 #if INCLUDE_JVMTI
2917 static void clear_all_breakpoints(Method* m) {
2918   m->clear_all_breakpoints();
2919 }
2920 #endif
2921 
2922 void InstanceKlass::unload_class(InstanceKlass* ik) {
2923   // Release dependencies.
2924   ik->dependencies().remove_all_dependents();
2925 
2926   // notify the debugger
2927   if (JvmtiExport::should_post_class_unload()) {
2928     JvmtiExport::post_class_unload(ik);
2929   }
2930 
2931   // notify ClassLoadingService of class unload
2932   ClassLoadingService::notify_class_unloaded(ik);
2933 

3663 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3664   for (int i = 0; i < len; i++) {
3665     intptr_t e = start[i];
3666     st->print("%d : " INTPTR_FORMAT, i, e);
3667     if (MetaspaceObj::is_valid((Metadata*)e)) {
3668       st->print(" ");
3669       ((Metadata*)e)->print_value_on(st);
3670     }
3671     st->cr();
3672   }
3673 }
3674 
3675 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3676   return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3677 }
3678 
3679 const char* InstanceKlass::init_state_name() const {
3680   return state_names[init_state()];
3681 }
3682 
3683 const char* InstanceKlass::state2name(ClassState s) {
3684   return state_names[s];
3685 }
3686 
3687 void InstanceKlass::print_on(outputStream* st) const {
3688   assert(is_klass(), "must be klass");
3689   Klass::print_on(st);
3690 
3691   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3692   st->print(BULLET"klass size:        %d", size());                               st->cr();
3693   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
3694   st->print(BULLET"flags:             "); _misc_flags.print_on(st);               st->cr();
3695   st->print(BULLET"state:             "); st->print_cr("%s", init_state_name());
3696   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3697   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3698   st->print(BULLET"sub:               ");
3699   Klass* sub = subklass();
3700   int n;
3701   for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3702     if (n < MaxSubklassPrintSize) {
3703       sub->print_value_on(st);
3704       st->print("   ");
3705     }
3706   }

4009         nullptr;
4010       // caller can be null, for example, during a JVMTI VM_Init hook
4011       if (caller != nullptr) {
4012         info_stream.print(" source: instance of %s", caller->external_name());
4013       } else {
4014         // source is unknown
4015       }
4016     } else {
4017       oop class_loader = loader_data->class_loader();
4018       info_stream.print(" source: %s", class_loader->klass()->external_name());
4019     }
4020   } else {
4021     assert(this->is_shared(), "must be");
4022     if (MetaspaceShared::is_shared_dynamic((void*)this)) {
4023       info_stream.print(" source: shared objects file (top)");
4024     } else {
4025       info_stream.print(" source: shared objects file");
4026     }
4027   }
4028 
4029   info_stream.print(" loader:");
4030   if (is_shared()) {
4031     info_stream.print(" %s", SystemDictionaryShared::class_loader_name_for_shared((Klass*)this));
4032   } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) {
4033     info_stream.print(" boot_loader");
4034   } else {
4035     oop class_loader = loader_data->class_loader();
4036     if (class_loader != nullptr) {
4037       info_stream.print(" %s", class_loader->klass()->external_name());
4038       oop cl_name_and_id = java_lang_ClassLoader::nameAndId(class_loader);
4039       if (cl_name_and_id != nullptr) {
4040         info_stream.print(" %s", java_lang_String::as_utf8_string(cl_name_and_id));
4041       }
4042     } else {
4043       info_stream.print(" null");
4044     }
4045   }
4046   msg.info("%s", info_stream.as_string());
4047 
4048   if (log_is_enabled(Debug, class, load)) {
4049     stringStream debug_stream;
4050 
4051     // Class hierarchy info
4052     debug_stream.print(" klass: " PTR_FORMAT " super: " PTR_FORMAT,
4053                        p2i(this),  p2i(superklass()));
4054 
4055     // Interfaces
4056     if (local_interfaces() != nullptr && local_interfaces()->length() > 0) {
4057       debug_stream.print(" interfaces:");
4058       int length = local_interfaces()->length();
4059       for (int i = 0; i < length; i++) {
4060         debug_stream.print(" " PTR_FORMAT,
4061                            p2i(InstanceKlass::cast(local_interfaces()->at(i))));
4062       }
4063     }
4064 
4065     // Class loader
< prev index next >