< prev index next >

src/hotspot/share/oops/instanceKlass.cpp

Print this page

  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/reflectionUtils.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"

 150 
 151 static inline bool is_class_loader(const Symbol* class_name,
 152                                    const ClassFileParser& parser) {
 153   assert(class_name != nullptr, "invariant");
 154 
 155   if (class_name == vmSymbols::java_lang_ClassLoader()) {
 156     return true;
 157   }
 158 
 159   if (vmClasses::ClassLoader_klass_loaded()) {
 160     const Klass* const super_klass = parser.super_klass();
 161     if (super_klass != nullptr) {
 162       if (super_klass->is_subtype_of(vmClasses::ClassLoader_klass())) {
 163         return true;
 164       }
 165     }
 166   }
 167   return false;
 168 }
 169 




 170 static inline bool is_stack_chunk_class(const Symbol* class_name,
 171                                         const ClassLoaderData* loader_data) {
 172   return (class_name == vmSymbols::jdk_internal_vm_StackChunk() &&
 173           loader_data->is_the_null_class_loader_data());
 174 }
 175 
 176 // private: called to verify that k is a static member of this nest.
 177 // We know that k is an instance class in the same package and hence the
 178 // same classloader.
 179 bool InstanceKlass::has_nest_member(JavaThread* current, InstanceKlass* k) const {
 180   assert(!is_hidden(), "unexpected hidden class");
 181   if (_nest_members == nullptr || _nest_members == Universe::the_empty_short_array()) {
 182     if (log_is_enabled(Trace, class, nestmates)) {
 183       ResourceMark rm(current);
 184       log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
 185                                   k->external_name(), this->external_name());
 186     }
 187     return false;
 188   }
 189 

 422   log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
 423                               this->external_name(),
 424                               access ? "" : "NOT ",
 425                               k->external_name());
 426   return access;
 427 }
 428 
 429 const char* InstanceKlass::nest_host_error() {
 430   if (_nest_host_index == 0) {
 431     return nullptr;
 432   } else {
 433     constantPoolHandle cph(Thread::current(), constants());
 434     return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index);
 435   }
 436 }
 437 
 438 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
 439   const int size = InstanceKlass::size(parser.vtable_size(),
 440                                        parser.itable_size(),
 441                                        nonstatic_oop_map_size(parser.total_oop_map_count()),
 442                                        parser.is_interface());


 443 
 444   const Symbol* const class_name = parser.class_name();
 445   assert(class_name != nullptr, "invariant");
 446   ClassLoaderData* loader_data = parser.loader_data();
 447   assert(loader_data != nullptr, "invariant");
 448 
 449   InstanceKlass* ik;
 450 
 451   // Allocation
 452   if (parser.is_instance_ref_klass()) {
 453     // java.lang.ref.Reference
 454     ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
 455   } else if (class_name == vmSymbols::java_lang_Class()) {
 456     // mirror - java.lang.Class
 457     ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
 458   } else if (is_stack_chunk_class(class_name, loader_data)) {
 459     // stack chunk
 460     ik = new (loader_data, size, THREAD) InstanceStackChunkKlass(parser);
 461   } else if (is_class_loader(class_name, parser)) {
 462     // class loader - java.lang.ClassLoader
 463     ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);



 464   } else {
 465     // normal
 466     ik = new (loader_data, size, THREAD) InstanceKlass(parser);
 467   }
 468 
 469   // Check for pending exception before adding to the loader data and incrementing
 470   // class count.  Can get OOM here.
 471   if (HAS_PENDING_EXCEPTION) {
 472     return nullptr;
 473   }
 474 






 475   return ik;
 476 }
 477 























 478 
 479 // copy method ordering from resource area to Metaspace
 480 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
 481   if (m != nullptr) {
 482     // allocate a new array and copy contents (memcpy?)
 483     _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
 484     for (int i = 0; i < m->length(); i++) {
 485       _method_ordering->at_put(i, m->at(i));
 486     }
 487   } else {
 488     _method_ordering = Universe::the_empty_int_array();
 489   }
 490 }
 491 
 492 // create a new array of vtable_indices for default methods
 493 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
 494   Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
 495   assert(default_vtable_indices() == nullptr, "only create once");
 496   set_default_vtable_indices(vtable_indices);
 497   return vtable_indices;

 501   return new Monitor(Mutex::safepoint, name);
 502 }
 503 
 504 InstanceKlass::InstanceKlass() {
 505   assert(CDSConfig::is_dumping_static_archive() || UseSharedSpaces, "only for CDS");
 506 }
 507 
 508 InstanceKlass::InstanceKlass(const ClassFileParser& parser, KlassKind kind, ReferenceType reference_type) :
 509   Klass(kind),
 510   _nest_members(nullptr),
 511   _nest_host(nullptr),
 512   _permitted_subclasses(nullptr),
 513   _record_components(nullptr),
 514   _static_field_size(parser.static_field_size()),
 515   _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
 516   _itable_len(parser.itable_size()),
 517   _nest_host_index(0),
 518   _init_state(allocated),
 519   _reference_type(reference_type),
 520   _init_monitor(create_init_monitor("InstanceKlassInitMonitor_lock")),
 521   _init_thread(nullptr)



 522 {
 523   set_vtable_length(parser.vtable_size());
 524   set_access_flags(parser.access_flags());
 525   if (parser.is_hidden()) set_is_hidden();
 526   set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
 527                                                     false));



 528 
 529   assert(nullptr == _methods, "underlying memory not zeroed?");
 530   assert(is_instance_klass(), "is layout incorrect?");
 531   assert(size_helper() == parser.layout_size(), "incorrect size_helper?");




 532 }
 533 
 534 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
 535                                        Array<Method*>* methods) {
 536   if (methods != nullptr && methods != Universe::the_empty_method_array() &&
 537       !methods->is_shared()) {
 538     for (int i = 0; i < methods->length(); i++) {
 539       Method* method = methods->at(i);
 540       if (method == nullptr) continue;  // maybe null if error processing
 541       // Only want to delete methods that are not executing for RedefineClasses.
 542       // The previous version will point to them so they're not totally dangling
 543       assert (!method->on_stack(), "shouldn't be called with methods on stack");
 544       MetadataFactory::free_metadata(loader_data, method);
 545     }
 546     MetadataFactory::free_array<Method*>(loader_data, methods);
 547   }
 548 }
 549 
 550 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
 551                                           const Klass* super_klass,

 681       inner_classes() != Universe::the_empty_short_array() &&
 682       !inner_classes()->is_shared()) {
 683     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
 684   }
 685   set_inner_classes(nullptr);
 686 
 687   if (nest_members() != nullptr &&
 688       nest_members() != Universe::the_empty_short_array() &&
 689       !nest_members()->is_shared()) {
 690     MetadataFactory::free_array<jushort>(loader_data, nest_members());
 691   }
 692   set_nest_members(nullptr);
 693 
 694   if (permitted_subclasses() != nullptr &&
 695       permitted_subclasses() != Universe::the_empty_short_array() &&
 696       !permitted_subclasses()->is_shared()) {
 697     MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
 698   }
 699   set_permitted_subclasses(nullptr);
 700 






 701   // We should deallocate the Annotations instance if it's not in shared spaces.
 702   if (annotations() != nullptr && !annotations()->is_shared()) {
 703     MetadataFactory::free_metadata(loader_data, annotations());
 704   }
 705   set_annotations(nullptr);
 706 
 707   SystemDictionaryShared::handle_class_unloading(this);
 708 
 709 #if INCLUDE_CDS_JAVA_HEAP
 710   if (CDSConfig::is_dumping_heap()) {
 711     HeapShared::remove_scratch_objects(this);
 712   }
 713 #endif
 714 }
 715 
 716 bool InstanceKlass::is_record() const {
 717   return _record_components != nullptr &&
 718          is_final() &&
 719          java_super() == vmClasses::Record_klass();
 720 }

 860         vmSymbols::java_lang_IncompatibleClassChangeError(),
 861         "class %s has interface %s as super class",
 862         external_name(),
 863         super_klass->external_name()
 864       );
 865       return false;
 866     }
 867 
 868     InstanceKlass* ik_super = InstanceKlass::cast(super_klass);
 869     ik_super->link_class_impl(CHECK_false);
 870   }
 871 
 872   // link all interfaces implemented by this class before linking this class
 873   Array<InstanceKlass*>* interfaces = local_interfaces();
 874   int num_interfaces = interfaces->length();
 875   for (int index = 0; index < num_interfaces; index++) {
 876     InstanceKlass* interk = interfaces->at(index);
 877     interk->link_class_impl(CHECK_false);
 878   }
 879 












































































 880   // in case the class is linked in the process of linking its superclasses
 881   if (is_linked()) {
 882     return true;
 883   }
 884 
 885   // trace only the link time for this klass that includes
 886   // the verification time
 887   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
 888                              ClassLoader::perf_class_link_selftime(),
 889                              ClassLoader::perf_classes_linked(),
 890                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 891                              jt->get_thread_stat()->perf_timers_addr(),
 892                              PerfClassTraceTime::CLASS_LINK);
 893 
 894   // verification & rewriting
 895   {
 896     LockLinkState init_lock(this, jt);
 897 
 898     // rewritten will have been set if loader constraint error found
 899     // on an earlier link attempt

1149       }
1150     }
1151   }
1152 
1153   // Throw error outside lock
1154   if (throw_error) {
1155     DTRACE_CLASSINIT_PROBE_WAIT(erroneous, -1, wait);
1156     ResourceMark rm(THREAD);
1157     Handle cause(THREAD, get_initialization_error(THREAD));
1158 
1159     stringStream ss;
1160     ss.print("Could not initialize class %s", external_name());
1161     if (cause.is_null()) {
1162       THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), ss.as_string());
1163     } else {
1164       THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1165                       ss.as_string(), cause);
1166     }
1167   }
1168 



















1169   // Step 7
1170   // Next, if C is a class rather than an interface, initialize it's super class and super
1171   // interfaces.
1172   if (!is_interface()) {
1173     Klass* super_klass = super();
1174     if (super_klass != nullptr && super_klass->should_be_initialized()) {
1175       super_klass->initialize(THREAD);
1176     }
1177     // If C implements any interface that declares a non-static, concrete method,
1178     // the initialization of C triggers initialization of its super interfaces.
1179     // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1180     // having a superinterface that declares, non-static, concrete methods
1181     if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1182       initialize_super_interfaces(THREAD);
1183     }
1184 
1185     // If any exceptions, complete abruptly, throwing the same exception as above.
1186     if (HAS_PENDING_EXCEPTION) {
1187       Handle e(THREAD, PENDING_EXCEPTION);
1188       CLEAR_PENDING_EXCEPTION;
1189       {
1190         EXCEPTION_MARK;
1191         add_initialization_error(THREAD, e);
1192         // Locks object, set state, and notify all waiting threads
1193         set_initialization_state_and_notify(initialization_error, THREAD);
1194         CLEAR_PENDING_EXCEPTION;
1195       }
1196       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1197       THROW_OOP(e());
1198     }
1199   }
1200 
1201 
1202   // Step 8









































1203   {
1204     DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1205     if (class_initializer() != nullptr) {
1206       // Timer includes any side effects of class initialization (resolution,
1207       // etc), but not recursive entry into call_class_initializer().
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(),

1536               : vmSymbols::java_lang_InstantiationException(), external_name());
1537   }
1538   if (this == vmClasses::Class_klass()) {
1539     ResourceMark rm(THREAD);
1540     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1541               : vmSymbols::java_lang_IllegalAccessException(), external_name());
1542   }
1543 }
1544 
1545 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
1546   // Need load-acquire for lock-free read
1547   if (array_klasses_acquire() == nullptr) {
1548     ResourceMark rm(THREAD);
1549     JavaThread *jt = THREAD;
1550     {
1551       // Atomic creation of array_klasses
1552       MutexLocker ma(THREAD, MultiArray_lock);
1553 
1554       // Check if update has already taken place
1555       if (array_klasses() == nullptr) {
1556         ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);

1557         // use 'release' to pair with lock-free load
1558         release_set_array_klasses(k);
1559       }
1560     }
1561   }
1562   // array_klasses() will always be set at this point
1563   ObjArrayKlass* oak = array_klasses();
1564   return oak->array_klass(n, THREAD);
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;

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   // Lock-free access requires load_acquire.
1639   OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache);
1640   if (oop_map_cache == nullptr) {
1641     MutexLocker x(OopMapCacheAlloc_lock);
1642     // Check if _oop_map_cache was allocated while we were waiting for this lock
1643     if ((oop_map_cache = _oop_map_cache) == nullptr) {
1644       oop_map_cache = new OopMapCache();
1645       // Ensure _oop_map_cache is stable, since it is examined without a lock
1646       Atomic::release_store(&_oop_map_cache, oop_map_cache);
1647     }
1648   }
1649   // _oop_map_cache is constant after init; lookup below does its own locking.
1650   oop_map_cache->lookup(method, bci, entry_for);
1651 }
1652 
1653 bool InstanceKlass::contains_field_offset(int offset) {
1654   fieldDescriptor fd;
1655   return find_field_from_offset(offset, false, &fd);
1656 }
1657 
1658 FieldInfo InstanceKlass::field(int index) const {
1659   for (AllFieldStream fs(this); !fs.done(); fs.next()) {
1660     if (fs.index() == index) {
1661       return fs.to_FieldInfo();
1662     }
1663   }
1664   fatal("Field not found");
1665   return FieldInfo();
1666 }
1667 
1668 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1669   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1670     Symbol* f_name = fs.name();
1671     Symbol* f_sig  = fs.signature();
1672     if (f_name == name && f_sig == sig) {
1673       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1674       return true;
1675     }
1676   }

1718 
1719 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1720   // search order according to newest JVM spec (5.4.3.2, p.167).
1721   // 1) search for field in current klass
1722   if (find_local_field(name, sig, fd)) {
1723     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1724   }
1725   // 2) search for field recursively in direct superinterfaces
1726   if (is_static) {
1727     Klass* intf = find_interface_field(name, sig, fd);
1728     if (intf != nullptr) return intf;
1729   }
1730   // 3) apply field lookup recursively if superclass exists
1731   { Klass* supr = super();
1732     if (supr != nullptr) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
1733   }
1734   // 4) otherwise field lookup fails
1735   return nullptr;
1736 }
1737 









1738 
1739 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1740   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1741     if (fs.offset() == offset) {
1742       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1743       if (fd->is_static() == is_static) return true;
1744     }
1745   }
1746   return false;
1747 }
1748 
1749 
1750 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1751   Klass* klass = const_cast<InstanceKlass*>(this);
1752   while (klass != nullptr) {
1753     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
1754       return true;
1755     }
1756     klass = klass->super();
1757   }

2109 }
2110 
2111 // uncached_lookup_method searches both the local class methods array and all
2112 // superclasses methods arrays, skipping any overpass methods in superclasses,
2113 // and possibly skipping private methods.
2114 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2115                                               const Symbol* signature,
2116                                               OverpassLookupMode overpass_mode,
2117                                               PrivateLookupMode private_mode) const {
2118   OverpassLookupMode overpass_local_mode = overpass_mode;
2119   const Klass* klass = this;
2120   while (klass != nullptr) {
2121     Method* const method = InstanceKlass::cast(klass)->find_method_impl(name,
2122                                                                         signature,
2123                                                                         overpass_local_mode,
2124                                                                         StaticLookupMode::find,
2125                                                                         private_mode);
2126     if (method != nullptr) {
2127       return method;
2128     }



2129     klass = klass->super();
2130     overpass_local_mode = OverpassLookupMode::skip;   // Always ignore overpass methods in superclasses
2131   }
2132   return nullptr;
2133 }
2134 
2135 #ifdef ASSERT
2136 // search through class hierarchy and return true if this class or
2137 // one of the superclasses was redefined
2138 bool InstanceKlass::has_redefined_this_or_super() const {
2139   const Klass* klass = this;
2140   while (klass != nullptr) {
2141     if (InstanceKlass::cast(klass)->has_been_redefined()) {
2142       return true;
2143     }
2144     klass = klass->super();
2145   }
2146   return false;
2147 }
2148 #endif

2590     int method_table_offset_in_words = ioe->offset()/wordSize;
2591     int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2592 
2593     int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2594                          / itableOffsetEntry::size();
2595 
2596     for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2597       if (ioe->interface_klass() != nullptr) {
2598         it->push(ioe->interface_klass_addr());
2599         itableMethodEntry* ime = ioe->first_method_entry(this);
2600         int n = klassItable::method_count_for_interface(ioe->interface_klass());
2601         for (int index = 0; index < n; index ++) {
2602           it->push(ime[index].method_addr());
2603         }
2604       }
2605     }
2606   }
2607 
2608   it->push(&_nest_members);
2609   it->push(&_permitted_subclasses);

2610   it->push(&_record_components);






2611 }
2612 
2613 #if INCLUDE_CDS
2614 void InstanceKlass::remove_unshareable_info() {
2615 
2616   if (is_linked()) {
2617     assert(can_be_verified_at_dumptime(), "must be");
2618     // Remember this so we can avoid walking the hierarchy at runtime.
2619     set_verified_at_dump_time();
2620   }
2621 
2622   Klass::remove_unshareable_info();
2623 
2624   if (SystemDictionaryShared::has_class_failed_verification(this)) {
2625     // Classes are attempted to link during dumping and may fail,
2626     // but these classes are still in the dictionary and class list in CLD.
2627     // If the class has failed verification, there is nothing else to remove.
2628     return;
2629   }
2630 

2634   // being added to class hierarchy (see InstanceKlass:::add_to_hierarchy()).
2635   _init_state = allocated;
2636 
2637   { // Otherwise this needs to take out the Compile_lock.
2638     assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2639     init_implementor();
2640   }
2641 
2642   constants()->remove_unshareable_info();
2643 
2644   for (int i = 0; i < methods()->length(); i++) {
2645     Method* m = methods()->at(i);
2646     m->remove_unshareable_info();
2647   }
2648 
2649   // do array classes also.
2650   if (array_klasses() != nullptr) {
2651     array_klasses()->remove_unshareable_info();
2652   }
2653 
2654   // These are not allocated from metaspace. They are safe to set to null.








2655   _source_debug_extension = nullptr;
2656   _dep_context = nullptr;
2657   _osr_nmethods_head = nullptr;
2658 #if INCLUDE_JVMTI
2659   _breakpoints = nullptr;
2660   _previous_versions = nullptr;
2661   _cached_class_file = nullptr;
2662   _jvmti_cached_class_field_map = nullptr;
2663 #endif
2664 
2665   _init_thread = nullptr;
2666   _methods_jmethod_ids = nullptr;
2667   _jni_ids = nullptr;
2668   _oop_map_cache = nullptr;
2669   // clear _nest_host to ensure re-load at runtime
2670   _nest_host = nullptr;
2671   init_shared_package_entry();
2672   _dep_context_last_cleaned = 0;
2673   _init_monitor = nullptr;
2674 

2719 void InstanceKlass::compute_has_loops_flag_for_methods() {
2720   Array<Method*>* methods = this->methods();
2721   for (int index = 0; index < methods->length(); ++index) {
2722     Method* m = methods->at(index);
2723     if (!m->is_overpass()) { // work around JDK-8305771
2724       m->compute_has_loops_flag();
2725     }
2726   }
2727 }
2728 
2729 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
2730                                              PackageEntry* pkg_entry, TRAPS) {
2731   // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
2732   // before the InstanceKlass is added to the SystemDictionary. Make
2733   // sure the current state is <loaded.
2734   assert(!is_loaded(), "invalid init state");
2735   assert(!shared_loading_failed(), "Must not try to load failed class again");
2736   set_package(loader_data, pkg_entry, CHECK);
2737   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2738 




2739   Array<Method*>* methods = this->methods();
2740   int num_methods = methods->length();
2741   for (int index = 0; index < num_methods; ++index) {
2742     methods->at(index)->restore_unshareable_info(CHECK);
2743   }
2744 #if INCLUDE_JVMTI
2745   if (JvmtiExport::has_redefined_a_class()) {
2746     // Reinitialize vtable because RedefineClasses may have changed some
2747     // entries in this vtable for super classes so the CDS vtable might
2748     // point to old or obsolete entries.  RedefineClasses doesn't fix up
2749     // vtables in the shared system dictionary, only the main one.
2750     // It also redefines the itable too so fix that too.
2751     // First fix any default methods that point to a super class that may
2752     // have been redefined.
2753     bool trace_name_printed = false;
2754     adjust_default_methods(&trace_name_printed);
2755     vtable().initialize_vtable();
2756     itable().initialize_itable();
2757   }
2758 #endif
2759 
2760   // restore constant pool resolved references
2761   constants()->restore_unshareable_info(CHECK);
2762 
2763   if (array_klasses() != nullptr) {
2764     // To get a consistent list of classes we need MultiArray_lock to ensure
2765     // array classes aren't observed while they are being restored.
2766     MutexLocker ml(MultiArray_lock);
2767     assert(this == array_klasses()->bottom_klass(), "sanity");
2768     // Array classes have null protection domain.
2769     // --> see ArrayKlass::complete_create_array_klass()
2770     array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
2771   }
2772 
2773   // Initialize @ValueBased class annotation
2774   if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation()) {
2775     set_is_value_based();
2776   }
2777 
2778   // restore the monitor
2779   _init_monitor = create_init_monitor("InstanceKlassInitMonitorRestored_lock");
2780 }
2781 
2782 // Check if a class or any of its supertypes has a version older than 50.
2783 // CDS will not perform verification of old classes during dump time because
2784 // without changing the old verifier, the verification constraint cannot be
2785 // retrieved during dump time.
2786 // Verification of archived old classes will be performed during run time.
2787 bool InstanceKlass::can_be_verified_at_dumptime() const {

2946   } else {
2947     // Adding one to the attribute length in order to store a null terminator
2948     // character could cause an overflow because the attribute length is
2949     // already coded with an u4 in the classfile, but in practice, it's
2950     // unlikely to happen.
2951     assert((length+1) > length, "Overflow checking");
2952     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2953     for (int i = 0; i < length; i++) {
2954       sde[i] = array[i];
2955     }
2956     sde[length] = '\0';
2957     _source_debug_extension = sde;
2958   }
2959 }
2960 
2961 Symbol* InstanceKlass::generic_signature() const                   { return _constants->generic_signature(); }
2962 u2 InstanceKlass::generic_signature_index() const                  { return _constants->generic_signature_index(); }
2963 void InstanceKlass::set_generic_signature_index(u2 sig_index)      { _constants->set_generic_signature_index(sig_index); }
2964 
2965 const char* InstanceKlass::signature_name() const {


2966 

2967   // Get the internal name as a c string
2968   const char* src = (const char*) (name()->as_C_string());
2969   const int src_length = (int)strlen(src);
2970 
2971   char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
2972 
2973   // Add L as type indicator
2974   int dest_index = 0;
2975   dest[dest_index++] = JVM_SIGNATURE_CLASS;
2976 
2977   // Add the actual class name
2978   for (int src_index = 0; src_index < src_length; ) {
2979     dest[dest_index++] = src[src_index++];
2980   }
2981 
2982   if (is_hidden()) { // Replace the last '+' with a '.'.
2983     for (int index = (int)src_length; index > 0; index--) {
2984       if (dest[index] == '+') {
2985         dest[index] = JVM_SIGNATURE_DOT;
2986         break;
2987       }
2988     }
2989   }
2990 
2991   // Add the semicolon and the null
2992   dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
2993   dest[dest_index] = '\0';
2994   return dest;
2995 }

3297 jint InstanceKlass::compute_modifier_flags() const {
3298   jint access = access_flags().as_int();
3299 
3300   // But check if it happens to be member class.
3301   InnerClassesIterator iter(this);
3302   for (; !iter.done(); iter.next()) {
3303     int ioff = iter.inner_class_info_index();
3304     // Inner class attribute can be zero, skip it.
3305     // Strange but true:  JVM spec. allows null inner class refs.
3306     if (ioff == 0) continue;
3307 
3308     // only look at classes that are already loaded
3309     // since we are looking for the flags for our self.
3310     Symbol* inner_name = constants()->klass_name_at(ioff);
3311     if (name() == inner_name) {
3312       // This is really a member class.
3313       access = iter.inner_access_flags();
3314       break;
3315     }
3316   }
3317   // Remember to strip ACC_SUPER bit
3318   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
3319 }
3320 
3321 jint InstanceKlass::jvmti_class_status() const {
3322   jint result = 0;
3323 
3324   if (is_linked()) {
3325     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3326   }
3327 
3328   if (is_initialized()) {
3329     assert(is_linked(), "Class status is not consistent");
3330     result |= JVMTI_CLASS_STATUS_INITIALIZED;
3331   }
3332   if (is_in_error_state()) {
3333     result |= JVMTI_CLASS_STATUS_ERROR;
3334   }
3335   return result;
3336 }
3337 
3338 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {

3552     }
3553     osr = osr->osr_link();
3554   }
3555 
3556   assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
3557   if (best != nullptr && best->comp_level() >= comp_level) {
3558     return best;
3559   }
3560   return nullptr;
3561 }
3562 
3563 // -----------------------------------------------------------------------------------------------------
3564 // Printing
3565 
3566 #define BULLET  " - "
3567 
3568 static const char* state_names[] = {
3569   "allocated", "loaded", "being_linked", "linked", "being_initialized", "fully_initialized", "initialization_error"
3570 };
3571 
3572 static void print_vtable(intptr_t* start, int len, outputStream* st) {



3573   for (int i = 0; i < len; i++) {
3574     intptr_t e = start[i];
3575     st->print("%d : " INTPTR_FORMAT, i, e);





3576     if (MetaspaceObj::is_valid((Metadata*)e)) {
3577       st->print(" ");
3578       ((Metadata*)e)->print_value_on(st);






3579     }
3580     st->cr();
3581   }
3582 }
3583 
3584 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3585   return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);





















3586 }
3587 
3588 const char* InstanceKlass::init_state_name() const {
3589   return state_names[init_state()];
3590 }
3591 
3592 void InstanceKlass::print_on(outputStream* st) const {
3593   assert(is_klass(), "must be klass");
3594   Klass::print_on(st);
3595 
3596   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3597   st->print(BULLET"klass size:        %d", size());                               st->cr();
3598   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
3599   st->print(BULLET"flags:             "); _misc_flags.print_on(st);               st->cr();
3600   st->print(BULLET"state:             "); st->print_cr("%s", init_state_name());
3601   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3602   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3603   st->print(BULLET"sub:               ");
3604   Klass* sub = subklass();
3605   int n;
3606   for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3607     if (n < MaxSubklassPrintSize) {
3608       sub->print_value_on(st);
3609       st->print("   ");
3610     }
3611   }
3612   if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize);
3613   st->cr();
3614 
3615   if (is_interface()) {
3616     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
3617     if (nof_implementors() == 1) {
3618       st->print_cr(BULLET"implementor:    ");
3619       st->print("   ");
3620       implementor()->print_value_on(st);
3621       st->cr();
3622     }
3623   }
3624 
3625   st->print(BULLET"arrays:            "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3626   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
3627   if (Verbose || WizardMode) {
3628     Array<Method*>* method_array = methods();
3629     for (int i = 0; i < method_array->length(); i++) {
3630       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3631     }
3632   }
3633   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
3634   st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
3635   if (Verbose && default_methods() != nullptr) {
3636     Array<Method*>* method_array = default_methods();
3637     for (int i = 0; i < method_array->length(); i++) {
3638       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3639     }
3640   }
3641   if (default_vtable_indices() != nullptr) {
3642     st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
3643   }
3644   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
3645   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3646   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
3647   if (class_loader_data() != nullptr) {
3648     st->print(BULLET"class loader data:  ");
3649     class_loader_data()->print_value_on(st);
3650     st->cr();
3651   }
3652   if (source_file_name() != nullptr) {
3653     st->print(BULLET"source file:       ");
3654     source_file_name()->print_value_on(st);
3655     st->cr();
3656   }
3657   if (source_debug_extension() != nullptr) {
3658     st->print(BULLET"source debug extension:       ");
3659     st->print("%s", source_debug_extension());
3660     st->cr();
3661   }
3662   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
3663   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
3664   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
3665   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();

3671          pv_node = pv_node->previous_versions()) {
3672       if (!have_pv)
3673         st->print(BULLET"previous version:  ");
3674       have_pv = true;
3675       pv_node->constants()->print_value_on(st);
3676     }
3677     if (have_pv) st->cr();
3678   }
3679 
3680   if (generic_signature() != nullptr) {
3681     st->print(BULLET"generic signature: ");
3682     generic_signature()->print_value_on(st);
3683     st->cr();
3684   }
3685   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
3686   st->print(BULLET"nest members:     "); nest_members()->print_value_on(st);     st->cr();
3687   if (record_components() != nullptr) {
3688     st->print(BULLET"record components:     "); record_components()->print_value_on(st);     st->cr();
3689   }
3690   st->print(BULLET"permitted subclasses:     "); permitted_subclasses()->print_value_on(st);     st->cr();

3691   if (java_mirror() != nullptr) {
3692     st->print(BULLET"java mirror:       ");
3693     java_mirror()->print_value_on(st);
3694     st->cr();
3695   } else {
3696     st->print_cr(BULLET"java mirror:       null");
3697   }
3698   st->print(BULLET"vtable length      %d  (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3699   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
3700   st->print(BULLET"itable length      %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3701   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
3702   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3703   FieldPrinter print_static_field(st);
3704   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3705   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3706   FieldPrinter print_nonstatic_field(st);
3707   InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3708   ik->print_nonstatic_fields(&print_nonstatic_field);
3709 
3710   st->print(BULLET"non-static oop maps: ");
3711   OopMapBlock* map     = start_of_nonstatic_oop_maps();
3712   OopMapBlock* end_map = map + nonstatic_oop_map_count();
3713   while (map < end_map) {
3714     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3715     map++;
3716   }
3717   st->cr();
3718 }
3719 
3720 void InstanceKlass::print_value_on(outputStream* st) const {
3721   assert(is_klass(), "must be klass");

  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 "oops/inlineKlass.hpp"
  75 #include "prims/jvmtiExport.hpp"
  76 #include "prims/jvmtiRedefineClasses.hpp"
  77 #include "prims/jvmtiThreadState.hpp"
  78 #include "prims/methodComparator.hpp"
  79 #include "runtime/arguments.hpp"
  80 #include "runtime/deoptimization.hpp"
  81 #include "runtime/atomic.hpp"
  82 #include "runtime/fieldDescriptor.inline.hpp"
  83 #include "runtime/handles.inline.hpp"
  84 #include "runtime/javaCalls.hpp"
  85 #include "runtime/javaThread.inline.hpp"
  86 #include "runtime/mutexLocker.hpp"
  87 #include "runtime/orderAccess.hpp"
  88 #include "runtime/os.inline.hpp"
  89 #include "runtime/reflectionUtils.hpp"
  90 #include "runtime/threads.hpp"
  91 #include "services/classLoadingService.hpp"
  92 #include "services/finalizerService.hpp"
  93 #include "services/threadService.hpp"
  94 #include "utilities/dtrace.hpp"

 151 
 152 static inline bool is_class_loader(const Symbol* class_name,
 153                                    const ClassFileParser& parser) {
 154   assert(class_name != nullptr, "invariant");
 155 
 156   if (class_name == vmSymbols::java_lang_ClassLoader()) {
 157     return true;
 158   }
 159 
 160   if (vmClasses::ClassLoader_klass_loaded()) {
 161     const Klass* const super_klass = parser.super_klass();
 162     if (super_klass != nullptr) {
 163       if (super_klass->is_subtype_of(vmClasses::ClassLoader_klass())) {
 164         return true;
 165       }
 166     }
 167   }
 168   return false;
 169 }
 170 
 171 bool InstanceKlass::field_is_null_free_inline_type(int index) const {
 172   return field(index).field_flags().is_null_free_inline_type();
 173 }
 174 
 175 static inline bool is_stack_chunk_class(const Symbol* class_name,
 176                                         const ClassLoaderData* loader_data) {
 177   return (class_name == vmSymbols::jdk_internal_vm_StackChunk() &&
 178           loader_data->is_the_null_class_loader_data());
 179 }
 180 
 181 // private: called to verify that k is a static member of this nest.
 182 // We know that k is an instance class in the same package and hence the
 183 // same classloader.
 184 bool InstanceKlass::has_nest_member(JavaThread* current, InstanceKlass* k) const {
 185   assert(!is_hidden(), "unexpected hidden class");
 186   if (_nest_members == nullptr || _nest_members == Universe::the_empty_short_array()) {
 187     if (log_is_enabled(Trace, class, nestmates)) {
 188       ResourceMark rm(current);
 189       log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
 190                                   k->external_name(), this->external_name());
 191     }
 192     return false;
 193   }
 194 

 427   log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
 428                               this->external_name(),
 429                               access ? "" : "NOT ",
 430                               k->external_name());
 431   return access;
 432 }
 433 
 434 const char* InstanceKlass::nest_host_error() {
 435   if (_nest_host_index == 0) {
 436     return nullptr;
 437   } else {
 438     constantPoolHandle cph(Thread::current(), constants());
 439     return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index);
 440   }
 441 }
 442 
 443 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
 444   const int size = InstanceKlass::size(parser.vtable_size(),
 445                                        parser.itable_size(),
 446                                        nonstatic_oop_map_size(parser.total_oop_map_count()),
 447                                        parser.is_interface(),
 448                                        parser.has_inline_fields() ? parser.java_fields_count() : 0,
 449                                        parser.is_inline_type());
 450 
 451   const Symbol* const class_name = parser.class_name();
 452   assert(class_name != nullptr, "invariant");
 453   ClassLoaderData* loader_data = parser.loader_data();
 454   assert(loader_data != nullptr, "invariant");
 455 
 456   InstanceKlass* ik;
 457 
 458   // Allocation
 459   if (parser.is_instance_ref_klass()) {
 460     // java.lang.ref.Reference
 461     ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
 462   } else if (class_name == vmSymbols::java_lang_Class()) {
 463     // mirror - java.lang.Class
 464     ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
 465   } else if (is_stack_chunk_class(class_name, loader_data)) {
 466     // stack chunk
 467     ik = new (loader_data, size, THREAD) InstanceStackChunkKlass(parser);
 468   } else if (is_class_loader(class_name, parser)) {
 469     // class loader - java.lang.ClassLoader
 470     ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);
 471   } else if (parser.is_inline_type()) {
 472     // inline type
 473     ik = new (loader_data, size, THREAD) InlineKlass(parser);
 474   } else {
 475     // normal
 476     ik = new (loader_data, size, THREAD) InstanceKlass(parser);
 477   }
 478 
 479   // Check for pending exception before adding to the loader data and incrementing
 480   // class count.  Can get OOM here.
 481   if (HAS_PENDING_EXCEPTION) {
 482     return nullptr;
 483   }
 484 
 485 #ifdef ASSERT
 486   ik->bounds_check((address) ik->start_of_vtable(), false, size);
 487   ik->bounds_check((address) ik->start_of_itable(), false, size);
 488   ik->bounds_check((address) ik->end_of_itable(), true, size);
 489   ik->bounds_check((address) ik->end_of_nonstatic_oop_maps(), true, size);
 490 #endif //ASSERT
 491   return ik;
 492 }
 493 
 494 #ifndef PRODUCT
 495 bool InstanceKlass::bounds_check(address addr, bool edge_ok, intptr_t size_in_bytes) const {
 496   const char* bad = nullptr;
 497   address end = nullptr;
 498   if (addr < (address)this) {
 499     bad = "before";
 500   } else if (addr == (address)this) {
 501     if (edge_ok)  return true;
 502     bad = "just before";
 503   } else if (addr == (end = (address)this + sizeof(intptr_t) * (size_in_bytes < 0 ? size() : size_in_bytes))) {
 504     if (edge_ok)  return true;
 505     bad = "just after";
 506   } else if (addr > end) {
 507     bad = "after";
 508   } else {
 509     return true;
 510   }
 511   tty->print_cr("%s object bounds: " INTPTR_FORMAT " [" INTPTR_FORMAT ".." INTPTR_FORMAT "]",
 512       bad, (intptr_t)addr, (intptr_t)this, (intptr_t)end);
 513   Verbose = WizardMode = true; this->print(); //@@
 514   return false;
 515 }
 516 #endif //PRODUCT
 517 
 518 // copy method ordering from resource area to Metaspace
 519 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
 520   if (m != nullptr) {
 521     // allocate a new array and copy contents (memcpy?)
 522     _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
 523     for (int i = 0; i < m->length(); i++) {
 524       _method_ordering->at_put(i, m->at(i));
 525     }
 526   } else {
 527     _method_ordering = Universe::the_empty_int_array();
 528   }
 529 }
 530 
 531 // create a new array of vtable_indices for default methods
 532 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
 533   Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
 534   assert(default_vtable_indices() == nullptr, "only create once");
 535   set_default_vtable_indices(vtable_indices);
 536   return vtable_indices;

 540   return new Monitor(Mutex::safepoint, name);
 541 }
 542 
 543 InstanceKlass::InstanceKlass() {
 544   assert(CDSConfig::is_dumping_static_archive() || UseSharedSpaces, "only for CDS");
 545 }
 546 
 547 InstanceKlass::InstanceKlass(const ClassFileParser& parser, KlassKind kind, ReferenceType reference_type) :
 548   Klass(kind),
 549   _nest_members(nullptr),
 550   _nest_host(nullptr),
 551   _permitted_subclasses(nullptr),
 552   _record_components(nullptr),
 553   _static_field_size(parser.static_field_size()),
 554   _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
 555   _itable_len(parser.itable_size()),
 556   _nest_host_index(0),
 557   _init_state(allocated),
 558   _reference_type(reference_type),
 559   _init_monitor(create_init_monitor("InstanceKlassInitMonitor_lock")),
 560   _init_thread(nullptr),
 561   _inline_type_field_klasses(nullptr),
 562   _preload_classes(nullptr),
 563   _adr_inlineklass_fixed_block(nullptr)
 564 {
 565   set_vtable_length(parser.vtable_size());
 566   set_access_flags(parser.access_flags());
 567   if (parser.is_hidden()) set_is_hidden();
 568   set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
 569                                                     false));
 570   if (parser.has_inline_fields()) {
 571     set_has_inline_type_fields();
 572   }
 573 
 574   assert(nullptr == _methods, "underlying memory not zeroed?");
 575   assert(is_instance_klass(), "is layout incorrect?");
 576   assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
 577 
 578   if (has_inline_type_fields()) {
 579     _inline_type_field_klasses = (const Klass**) adr_inline_type_field_klasses();
 580   }
 581 }
 582 
 583 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
 584                                        Array<Method*>* methods) {
 585   if (methods != nullptr && methods != Universe::the_empty_method_array() &&
 586       !methods->is_shared()) {
 587     for (int i = 0; i < methods->length(); i++) {
 588       Method* method = methods->at(i);
 589       if (method == nullptr) continue;  // maybe null if error processing
 590       // Only want to delete methods that are not executing for RedefineClasses.
 591       // The previous version will point to them so they're not totally dangling
 592       assert (!method->on_stack(), "shouldn't be called with methods on stack");
 593       MetadataFactory::free_metadata(loader_data, method);
 594     }
 595     MetadataFactory::free_array<Method*>(loader_data, methods);
 596   }
 597 }
 598 
 599 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
 600                                           const Klass* super_klass,

 730       inner_classes() != Universe::the_empty_short_array() &&
 731       !inner_classes()->is_shared()) {
 732     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
 733   }
 734   set_inner_classes(nullptr);
 735 
 736   if (nest_members() != nullptr &&
 737       nest_members() != Universe::the_empty_short_array() &&
 738       !nest_members()->is_shared()) {
 739     MetadataFactory::free_array<jushort>(loader_data, nest_members());
 740   }
 741   set_nest_members(nullptr);
 742 
 743   if (permitted_subclasses() != nullptr &&
 744       permitted_subclasses() != Universe::the_empty_short_array() &&
 745       !permitted_subclasses()->is_shared()) {
 746     MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
 747   }
 748   set_permitted_subclasses(nullptr);
 749 
 750   if (preload_classes() != nullptr &&
 751       preload_classes() != Universe::the_empty_short_array() &&
 752       !preload_classes()->is_shared()) {
 753     MetadataFactory::free_array<jushort>(loader_data, preload_classes());
 754   }
 755 
 756   // We should deallocate the Annotations instance if it's not in shared spaces.
 757   if (annotations() != nullptr && !annotations()->is_shared()) {
 758     MetadataFactory::free_metadata(loader_data, annotations());
 759   }
 760   set_annotations(nullptr);
 761 
 762   SystemDictionaryShared::handle_class_unloading(this);
 763 
 764 #if INCLUDE_CDS_JAVA_HEAP
 765   if (CDSConfig::is_dumping_heap()) {
 766     HeapShared::remove_scratch_objects(this);
 767   }
 768 #endif
 769 }
 770 
 771 bool InstanceKlass::is_record() const {
 772   return _record_components != nullptr &&
 773          is_final() &&
 774          java_super() == vmClasses::Record_klass();
 775 }

 915         vmSymbols::java_lang_IncompatibleClassChangeError(),
 916         "class %s has interface %s as super class",
 917         external_name(),
 918         super_klass->external_name()
 919       );
 920       return false;
 921     }
 922 
 923     InstanceKlass* ik_super = InstanceKlass::cast(super_klass);
 924     ik_super->link_class_impl(CHECK_false);
 925   }
 926 
 927   // link all interfaces implemented by this class before linking this class
 928   Array<InstanceKlass*>* interfaces = local_interfaces();
 929   int num_interfaces = interfaces->length();
 930   for (int index = 0; index < num_interfaces; index++) {
 931     InstanceKlass* interk = interfaces->at(index);
 932     interk->link_class_impl(CHECK_false);
 933   }
 934 
 935 
 936   // If a class declares a method that uses an inline class as an argument
 937   // type or return inline type, this inline class must be loaded during the
 938   // linking of this class because size and properties of the inline class
 939   // must be known in order to be able to perform inline type optimizations.
 940   // The implementation below is an approximation of this rule, the code
 941   // iterates over all methods of the current class (including overridden
 942   // methods), not only the methods declared by this class. This
 943   // approximation makes the code simpler, and doesn't change the semantic
 944   // because classes declaring methods overridden by the current class are
 945   // linked (and have performed their own pre-loading) before the linking
 946   // of the current class.
 947 
 948 
 949   // Note:
 950   // Inline class types are loaded during
 951   // the loading phase (see ClassFileParser::post_process_parsed_stream()).
 952   // Inline class types used as element types for array creation
 953   // are not pre-loaded. Their loading is triggered by either anewarray
 954   // or multianewarray bytecodes.
 955 
 956   // Could it be possible to do the following processing only if the
 957   // class uses inline types?
 958   if (EnableValhalla) {
 959     ResourceMark rm(THREAD);
 960     // Aggressively preloading all classes from the Preload attribute
 961     if (preload_classes() != nullptr) {
 962       for (int i = 0; i < preload_classes()->length(); i++) {
 963         if (constants()->tag_at(preload_classes()->at(i)).is_klass()) continue;
 964         Symbol* class_name = constants()->klass_at_noresolve(preload_classes()->at(i));
 965         if (class_name == name()) continue;
 966         oop loader = class_loader();
 967         oop protection_domain = this->protection_domain();
 968         Klass* klass = SystemDictionary::resolve_or_null(class_name,
 969                                                           Handle(THREAD, loader), Handle(THREAD, protection_domain), THREAD);
 970         if (HAS_PENDING_EXCEPTION) {
 971           CLEAR_PENDING_EXCEPTION;
 972         }
 973         if (klass != nullptr) {
 974           log_info(class, preload)("Preloading class %s during linking of class %s because of its Preload attribute", class_name->as_C_string(), name()->as_C_string());
 975         } else {
 976           log_warning(class, preload)("Preloading of class %s during linking of class %s (Preload attribute) failed", class_name->as_C_string(), name()->as_C_string());
 977         }
 978       }
 979     }
 980 
 981     for (AllFieldStream fs(this); !fs.done(); fs.next()) {
 982       if (fs.is_null_free_inline_type() && fs.access_flags().is_static()) {
 983         Symbol* sig = fs.signature();
 984         oop loader = class_loader();
 985         oop protection_domain = this->protection_domain();
 986         Klass* klass = SystemDictionary::resolve_or_fail(sig,
 987                                                         Handle(THREAD, loader), Handle(THREAD, protection_domain), true,
 988                                                         CHECK_false);
 989         if (klass == nullptr) {
 990           THROW_(vmSymbols::java_lang_LinkageError(), false);
 991         }
 992         if (!klass->is_inline_klass()) {
 993           Exceptions::fthrow(
 994             THREAD_AND_LOCATION,
 995             vmSymbols::java_lang_IncompatibleClassChangeError(),
 996             "class %s is not an inline type",
 997             klass->external_name());
 998         }
 999         InstanceKlass* ik = InstanceKlass::cast(klass);
1000         if (!ik->is_implicitly_constructible()) {
1001           Exceptions::fthrow(
1002             THREAD_AND_LOCATION,
1003             vmSymbols::java_lang_IncompatibleClassChangeError(),
1004             "class %s is not implicitly constructible and it is used in a null restricted static field (not supported)",
1005             klass->external_name());
1006         }
1007       }
1008     }
1009   }
1010 
1011   // in case the class is linked in the process of linking its superclasses
1012   if (is_linked()) {
1013     return true;
1014   }
1015 
1016   // trace only the link time for this klass that includes
1017   // the verification time
1018   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
1019                              ClassLoader::perf_class_link_selftime(),
1020                              ClassLoader::perf_classes_linked(),
1021                              jt->get_thread_stat()->perf_recursion_counts_addr(),
1022                              jt->get_thread_stat()->perf_timers_addr(),
1023                              PerfClassTraceTime::CLASS_LINK);
1024 
1025   // verification & rewriting
1026   {
1027     LockLinkState init_lock(this, jt);
1028 
1029     // rewritten will have been set if loader constraint error found
1030     // on an earlier link attempt

1280       }
1281     }
1282   }
1283 
1284   // Throw error outside lock
1285   if (throw_error) {
1286     DTRACE_CLASSINIT_PROBE_WAIT(erroneous, -1, wait);
1287     ResourceMark rm(THREAD);
1288     Handle cause(THREAD, get_initialization_error(THREAD));
1289 
1290     stringStream ss;
1291     ss.print("Could not initialize class %s", external_name());
1292     if (cause.is_null()) {
1293       THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), ss.as_string());
1294     } else {
1295       THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1296                       ss.as_string(), cause);
1297     }
1298   }
1299 
1300   // Pre-allocating an instance of the default value
1301   if (is_inline_klass()) {
1302       InlineKlass* vk = InlineKlass::cast(this);
1303       oop val = vk->allocate_instance(THREAD);
1304       if (HAS_PENDING_EXCEPTION) {
1305           Handle e(THREAD, PENDING_EXCEPTION);
1306           CLEAR_PENDING_EXCEPTION;
1307           {
1308               EXCEPTION_MARK;
1309               add_initialization_error(THREAD, e);
1310               // Locks object, set state, and notify all waiting threads
1311               set_initialization_state_and_notify(initialization_error, THREAD);
1312               CLEAR_PENDING_EXCEPTION;
1313           }
1314           THROW_OOP(e());
1315       }
1316       vk->set_default_value(val);
1317   }
1318 
1319   // Step 7
1320   // Next, if C is a class rather than an interface, initialize it's super class and super
1321   // interfaces.
1322   if (!is_interface()) {
1323     Klass* super_klass = super();
1324     if (super_klass != nullptr && super_klass->should_be_initialized()) {
1325       super_klass->initialize(THREAD);
1326     }
1327     // If C implements any interface that declares a non-static, concrete method,
1328     // the initialization of C triggers initialization of its super interfaces.
1329     // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1330     // having a superinterface that declares, non-static, concrete methods
1331     if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1332       initialize_super_interfaces(THREAD);
1333     }
1334 
1335     // If any exceptions, complete abruptly, throwing the same exception as above.
1336     if (HAS_PENDING_EXCEPTION) {
1337       Handle e(THREAD, PENDING_EXCEPTION);
1338       CLEAR_PENDING_EXCEPTION;
1339       {
1340         EXCEPTION_MARK;
1341         add_initialization_error(THREAD, e);
1342         // Locks object, set state, and notify all waiting threads
1343         set_initialization_state_and_notify(initialization_error, THREAD);
1344         CLEAR_PENDING_EXCEPTION;
1345       }
1346       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1347       THROW_OOP(e());
1348     }
1349   }
1350 

1351   // Step 8
1352   // Initialize classes of inline fields
1353   if (EnableValhalla) {
1354     for (AllFieldStream fs(this); !fs.done(); fs.next()) {
1355       if (fs.is_null_free_inline_type()) {
1356         Klass* klass = get_inline_type_field_klass_or_null(fs.index());
1357         if (fs.access_flags().is_static() && klass == nullptr) {
1358           klass = SystemDictionary::resolve_or_fail(field_signature(fs.index())->fundamental_name(THREAD),
1359               Handle(THREAD, class_loader()),
1360               Handle(THREAD, protection_domain()),
1361               true, THREAD);
1362           set_inline_type_field_klass(fs.index(), klass);
1363         }
1364 
1365         if (!HAS_PENDING_EXCEPTION) {
1366           assert(klass != nullptr, "Must  be");
1367           InstanceKlass::cast(klass)->initialize(THREAD);
1368           if (fs.access_flags().is_static()) {
1369             if (java_mirror()->obj_field(fs.offset()) == nullptr) {
1370               java_mirror()->obj_field_put(fs.offset(), InlineKlass::cast(klass)->default_value());
1371             }
1372           }
1373         }
1374 
1375         if (HAS_PENDING_EXCEPTION) {
1376           Handle e(THREAD, PENDING_EXCEPTION);
1377           CLEAR_PENDING_EXCEPTION;
1378           {
1379             EXCEPTION_MARK;
1380             add_initialization_error(THREAD, e);
1381             // Locks object, set state, and notify all waiting threads
1382             set_initialization_state_and_notify(initialization_error, THREAD);
1383             CLEAR_PENDING_EXCEPTION;
1384           }
1385           THROW_OOP(e());
1386         }
1387       }
1388     }
1389   }
1390 
1391 
1392   // Step 9
1393   {
1394     DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1395     if (class_initializer() != nullptr) {
1396       // Timer includes any side effects of class initialization (resolution,
1397       // etc), but not recursive entry into call_class_initializer().
1398       PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1399                                ClassLoader::perf_class_init_selftime(),
1400                                ClassLoader::perf_classes_inited(),
1401                                jt->get_thread_stat()->perf_recursion_counts_addr(),
1402                                jt->get_thread_stat()->perf_timers_addr(),
1403                                PerfClassTraceTime::CLASS_CLINIT);
1404       call_class_initializer(THREAD);
1405     } else {
1406       // The elapsed time is so small it's not worth counting.
1407       if (UsePerfData) {
1408         ClassLoader::perf_classes_inited()->inc();
1409       }
1410       call_class_initializer(THREAD);
1411     }
1412   }
1413 
1414   // Step 10
1415   if (!HAS_PENDING_EXCEPTION) {
1416     set_initialization_state_and_notify(fully_initialized, THREAD);
1417     debug_only(vtable().verify(tty, true);)
1418   }
1419   else {
1420     // Step 11 and 12
1421     Handle e(THREAD, PENDING_EXCEPTION);
1422     CLEAR_PENDING_EXCEPTION;
1423     // JVMTI has already reported the pending exception
1424     // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1425     JvmtiExport::clear_detected_exception(jt);
1426     {
1427       EXCEPTION_MARK;
1428       add_initialization_error(THREAD, e);
1429       set_initialization_state_and_notify(initialization_error, THREAD);
1430       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
1431       // JVMTI has already reported the pending exception
1432       // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1433       JvmtiExport::clear_detected_exception(jt);
1434     }
1435     DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1436     if (e->is_a(vmClasses::Error_klass())) {
1437       THROW_OOP(e());
1438     } else {
1439       JavaCallArguments args(e);
1440       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),

1726               : vmSymbols::java_lang_InstantiationException(), external_name());
1727   }
1728   if (this == vmClasses::Class_klass()) {
1729     ResourceMark rm(THREAD);
1730     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1731               : vmSymbols::java_lang_IllegalAccessException(), external_name());
1732   }
1733 }
1734 
1735 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
1736   // Need load-acquire for lock-free read
1737   if (array_klasses_acquire() == nullptr) {
1738     ResourceMark rm(THREAD);
1739     JavaThread *jt = THREAD;
1740     {
1741       // Atomic creation of array_klasses
1742       MutexLocker ma(THREAD, MultiArray_lock);
1743 
1744       // Check if update has already taken place
1745       if (array_klasses() == nullptr) {
1746         ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this,
1747                                                                   false, CHECK_NULL);
1748         // use 'release' to pair with lock-free load
1749         release_set_array_klasses(k);
1750       }
1751     }
1752   }
1753   // array_klasses() will always be set at this point
1754   ArrayKlass* ak = array_klasses();
1755   return ak->array_klass(n, THREAD);
1756 }
1757 
1758 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1759   // Need load-acquire for lock-free read
1760   ArrayKlass* ak = array_klasses_acquire();
1761   if (ak == nullptr) {
1762     return nullptr;
1763   } else {
1764     return ak->array_klass_or_null(n);
1765   }
1766 }
1767 
1768 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1769   return array_klass(1, THREAD);
1770 }
1771 
1772 ArrayKlass* InstanceKlass::array_klass_or_null() {
1773   return array_klass_or_null(1);
1774 }
1775 
1776 static int call_class_initializer_counter = 0;   // for debugging
1777 
1778 Method* InstanceKlass::class_initializer() const {
1779   Method* clinit = find_method(
1780       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1781   if (clinit != nullptr && clinit->is_class_initializer()) {
1782     return clinit;
1783   }
1784   return nullptr;
1785 }
1786 
1787 void InstanceKlass::call_class_initializer(TRAPS) {
1788   if (ReplayCompiles &&
1789       (ReplaySuppressInitializers == 1 ||
1790        (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1791     // Hide the existence of the initializer for the purpose of replaying the compile
1792     return;
1793   }
1794 
1795 #if INCLUDE_CDS
1796   // This is needed to ensure the consistency of the archived heap objects.
1797   if (has_archived_enum_objs()) {
1798     assert(is_shared(), "must be");
1799     bool initialized = HeapShared::initialize_enum_klass(this, CHECK);
1800     if (initialized) {
1801       return;

1812     ls.print("%d Initializing ", call_class_initializer_counter++);
1813     name()->print_value_on(&ls);
1814     ls.print_cr("%s (" PTR_FORMAT ") by thread \"%s\"",
1815                 h_method() == nullptr ? "(no method)" : "", p2i(this),
1816                 THREAD->name());
1817   }
1818   if (h_method() != nullptr) {
1819     JavaCallArguments args; // No arguments
1820     JavaValue result(T_VOID);
1821     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1822   }
1823 }
1824 
1825 
1826 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1827   InterpreterOopMap* entry_for) {
1828   // Lazily create the _oop_map_cache at first request
1829   // Lock-free access requires load_acquire.
1830   OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache);
1831   if (oop_map_cache == nullptr) {
1832     MutexLocker x(OopMapCacheAlloc_lock,  Mutex::_no_safepoint_check_flag);
1833     // Check if _oop_map_cache was allocated while we were waiting for this lock
1834     if ((oop_map_cache = _oop_map_cache) == nullptr) {
1835       oop_map_cache = new OopMapCache();
1836       // Ensure _oop_map_cache is stable, since it is examined without a lock
1837       Atomic::release_store(&_oop_map_cache, oop_map_cache);
1838     }
1839   }
1840   // _oop_map_cache is constant after init; lookup below does its own locking.
1841   oop_map_cache->lookup(method, bci, entry_for);
1842 }
1843 




1844 
1845 FieldInfo InstanceKlass::field(int index) const {
1846   for (AllFieldStream fs(this); !fs.done(); fs.next()) {
1847     if (fs.index() == index) {
1848       return fs.to_FieldInfo();
1849     }
1850   }
1851   fatal("Field not found");
1852   return FieldInfo();
1853 }
1854 
1855 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1856   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1857     Symbol* f_name = fs.name();
1858     Symbol* f_sig  = fs.signature();
1859     if (f_name == name && f_sig == sig) {
1860       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1861       return true;
1862     }
1863   }

1905 
1906 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1907   // search order according to newest JVM spec (5.4.3.2, p.167).
1908   // 1) search for field in current klass
1909   if (find_local_field(name, sig, fd)) {
1910     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1911   }
1912   // 2) search for field recursively in direct superinterfaces
1913   if (is_static) {
1914     Klass* intf = find_interface_field(name, sig, fd);
1915     if (intf != nullptr) return intf;
1916   }
1917   // 3) apply field lookup recursively if superclass exists
1918   { Klass* supr = super();
1919     if (supr != nullptr) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
1920   }
1921   // 4) otherwise field lookup fails
1922   return nullptr;
1923 }
1924 
1925 bool InstanceKlass::contains_field_offset(int offset) {
1926   if (this->is_inline_klass()) {
1927     InlineKlass* vk = InlineKlass::cast(this);
1928     return offset >= vk->first_field_offset() && offset < (vk->first_field_offset() + vk->get_exact_size_in_bytes());
1929   } else {
1930     fieldDescriptor fd;
1931     return find_field_from_offset(offset, false, &fd);
1932   }
1933 }
1934 
1935 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1936   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1937     if (fs.offset() == offset) {
1938       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1939       if (fd->is_static() == is_static) return true;
1940     }
1941   }
1942   return false;
1943 }
1944 
1945 
1946 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1947   Klass* klass = const_cast<InstanceKlass*>(this);
1948   while (klass != nullptr) {
1949     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
1950       return true;
1951     }
1952     klass = klass->super();
1953   }

2305 }
2306 
2307 // uncached_lookup_method searches both the local class methods array and all
2308 // superclasses methods arrays, skipping any overpass methods in superclasses,
2309 // and possibly skipping private methods.
2310 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2311                                               const Symbol* signature,
2312                                               OverpassLookupMode overpass_mode,
2313                                               PrivateLookupMode private_mode) const {
2314   OverpassLookupMode overpass_local_mode = overpass_mode;
2315   const Klass* klass = this;
2316   while (klass != nullptr) {
2317     Method* const method = InstanceKlass::cast(klass)->find_method_impl(name,
2318                                                                         signature,
2319                                                                         overpass_local_mode,
2320                                                                         StaticLookupMode::find,
2321                                                                         private_mode);
2322     if (method != nullptr) {
2323       return method;
2324     }
2325     if (name == vmSymbols::object_initializer_name()) {
2326       break;  // <init> is never inherited
2327     }
2328     klass = klass->super();
2329     overpass_local_mode = OverpassLookupMode::skip;   // Always ignore overpass methods in superclasses
2330   }
2331   return nullptr;
2332 }
2333 
2334 #ifdef ASSERT
2335 // search through class hierarchy and return true if this class or
2336 // one of the superclasses was redefined
2337 bool InstanceKlass::has_redefined_this_or_super() const {
2338   const Klass* klass = this;
2339   while (klass != nullptr) {
2340     if (InstanceKlass::cast(klass)->has_been_redefined()) {
2341       return true;
2342     }
2343     klass = klass->super();
2344   }
2345   return false;
2346 }
2347 #endif

2789     int method_table_offset_in_words = ioe->offset()/wordSize;
2790     int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2791 
2792     int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2793                          / itableOffsetEntry::size();
2794 
2795     for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2796       if (ioe->interface_klass() != nullptr) {
2797         it->push(ioe->interface_klass_addr());
2798         itableMethodEntry* ime = ioe->first_method_entry(this);
2799         int n = klassItable::method_count_for_interface(ioe->interface_klass());
2800         for (int index = 0; index < n; index ++) {
2801           it->push(ime[index].method_addr());
2802         }
2803       }
2804     }
2805   }
2806 
2807   it->push(&_nest_members);
2808   it->push(&_permitted_subclasses);
2809   it->push(&_preload_classes);
2810   it->push(&_record_components);
2811 
2812   if (has_inline_type_fields()) {
2813     for (int i = 0; i < java_fields_count(); i++) {
2814       it->push(&((Klass**)adr_inline_type_field_klasses())[i]);
2815     }
2816   }
2817 }
2818 
2819 #if INCLUDE_CDS
2820 void InstanceKlass::remove_unshareable_info() {
2821 
2822   if (is_linked()) {
2823     assert(can_be_verified_at_dumptime(), "must be");
2824     // Remember this so we can avoid walking the hierarchy at runtime.
2825     set_verified_at_dump_time();
2826   }
2827 
2828   Klass::remove_unshareable_info();
2829 
2830   if (SystemDictionaryShared::has_class_failed_verification(this)) {
2831     // Classes are attempted to link during dumping and may fail,
2832     // but these classes are still in the dictionary and class list in CLD.
2833     // If the class has failed verification, there is nothing else to remove.
2834     return;
2835   }
2836 

2840   // being added to class hierarchy (see InstanceKlass:::add_to_hierarchy()).
2841   _init_state = allocated;
2842 
2843   { // Otherwise this needs to take out the Compile_lock.
2844     assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2845     init_implementor();
2846   }
2847 
2848   constants()->remove_unshareable_info();
2849 
2850   for (int i = 0; i < methods()->length(); i++) {
2851     Method* m = methods()->at(i);
2852     m->remove_unshareable_info();
2853   }
2854 
2855   // do array classes also.
2856   if (array_klasses() != nullptr) {
2857     array_klasses()->remove_unshareable_info();
2858   }
2859 
2860   if (has_inline_type_fields()) {
2861     for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2862       if (fs.is_null_free_inline_type()) {
2863         reset_inline_type_field_klass(fs.index());
2864       }
2865     }
2866   }
2867 
2868   // These are not allocated from metaspace. They are safe to set to nullptr.
2869   _source_debug_extension = nullptr;
2870   _dep_context = nullptr;
2871   _osr_nmethods_head = nullptr;
2872 #if INCLUDE_JVMTI
2873   _breakpoints = nullptr;
2874   _previous_versions = nullptr;
2875   _cached_class_file = nullptr;
2876   _jvmti_cached_class_field_map = nullptr;
2877 #endif
2878 
2879   _init_thread = nullptr;
2880   _methods_jmethod_ids = nullptr;
2881   _jni_ids = nullptr;
2882   _oop_map_cache = nullptr;
2883   // clear _nest_host to ensure re-load at runtime
2884   _nest_host = nullptr;
2885   init_shared_package_entry();
2886   _dep_context_last_cleaned = 0;
2887   _init_monitor = nullptr;
2888 

2933 void InstanceKlass::compute_has_loops_flag_for_methods() {
2934   Array<Method*>* methods = this->methods();
2935   for (int index = 0; index < methods->length(); ++index) {
2936     Method* m = methods->at(index);
2937     if (!m->is_overpass()) { // work around JDK-8305771
2938       m->compute_has_loops_flag();
2939     }
2940   }
2941 }
2942 
2943 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
2944                                              PackageEntry* pkg_entry, TRAPS) {
2945   // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
2946   // before the InstanceKlass is added to the SystemDictionary. Make
2947   // sure the current state is <loaded.
2948   assert(!is_loaded(), "invalid init state");
2949   assert(!shared_loading_failed(), "Must not try to load failed class again");
2950   set_package(loader_data, pkg_entry, CHECK);
2951   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2952 
2953   if (is_inline_klass()) {
2954     InlineKlass::cast(this)->initialize_calling_convention(CHECK);
2955   }
2956 
2957   Array<Method*>* methods = this->methods();
2958   int num_methods = methods->length();
2959   for (int index = 0; index < num_methods; ++index) {
2960     methods->at(index)->restore_unshareable_info(CHECK);
2961   }
2962 #if INCLUDE_JVMTI
2963   if (JvmtiExport::has_redefined_a_class()) {
2964     // Reinitialize vtable because RedefineClasses may have changed some
2965     // entries in this vtable for super classes so the CDS vtable might
2966     // point to old or obsolete entries.  RedefineClasses doesn't fix up
2967     // vtables in the shared system dictionary, only the main one.
2968     // It also redefines the itable too so fix that too.
2969     // First fix any default methods that point to a super class that may
2970     // have been redefined.
2971     bool trace_name_printed = false;
2972     adjust_default_methods(&trace_name_printed);
2973     vtable().initialize_vtable();
2974     itable().initialize_itable();
2975   }
2976 #endif
2977 
2978   // restore constant pool resolved references
2979   constants()->restore_unshareable_info(CHECK);
2980 
2981   if (array_klasses() != nullptr) {
2982     // To get a consistent list of classes we need MultiArray_lock to ensure
2983     // array classes aren't observed while they are being restored.
2984     MutexLocker ml(MultiArray_lock);
2985     assert(this == ObjArrayKlass::cast(array_klasses())->bottom_klass(), "sanity");
2986     // Array classes have null protection domain.
2987     // --> see ArrayKlass::complete_create_array_klass()
2988     array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
2989   }
2990 
2991   // Initialize @ValueBased class annotation
2992   if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation()) {
2993     set_is_value_based();
2994   }
2995 
2996   // restore the monitor
2997   _init_monitor = create_init_monitor("InstanceKlassInitMonitorRestored_lock");
2998 }
2999 
3000 // Check if a class or any of its supertypes has a version older than 50.
3001 // CDS will not perform verification of old classes during dump time because
3002 // without changing the old verifier, the verification constraint cannot be
3003 // retrieved during dump time.
3004 // Verification of archived old classes will be performed during run time.
3005 bool InstanceKlass::can_be_verified_at_dumptime() const {

3164   } else {
3165     // Adding one to the attribute length in order to store a null terminator
3166     // character could cause an overflow because the attribute length is
3167     // already coded with an u4 in the classfile, but in practice, it's
3168     // unlikely to happen.
3169     assert((length+1) > length, "Overflow checking");
3170     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
3171     for (int i = 0; i < length; i++) {
3172       sde[i] = array[i];
3173     }
3174     sde[length] = '\0';
3175     _source_debug_extension = sde;
3176   }
3177 }
3178 
3179 Symbol* InstanceKlass::generic_signature() const                   { return _constants->generic_signature(); }
3180 u2 InstanceKlass::generic_signature_index() const                  { return _constants->generic_signature_index(); }
3181 void InstanceKlass::set_generic_signature_index(u2 sig_index)      { _constants->set_generic_signature_index(sig_index); }
3182 
3183 const char* InstanceKlass::signature_name() const {
3184   return signature_name_of_carrier(JVM_SIGNATURE_CLASS);
3185 }
3186 
3187 const char* InstanceKlass::signature_name_of_carrier(char c) const {
3188   // Get the internal name as a c string
3189   const char* src = (const char*) (name()->as_C_string());
3190   const int src_length = (int)strlen(src);
3191 
3192   char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
3193 
3194   // Add L or Q as type indicator
3195   int dest_index = 0;
3196   dest[dest_index++] = c;
3197 
3198   // Add the actual class name
3199   for (int src_index = 0; src_index < src_length; ) {
3200     dest[dest_index++] = src[src_index++];
3201   }
3202 
3203   if (is_hidden()) { // Replace the last '+' with a '.'.
3204     for (int index = (int)src_length; index > 0; index--) {
3205       if (dest[index] == '+') {
3206         dest[index] = JVM_SIGNATURE_DOT;
3207         break;
3208       }
3209     }
3210   }
3211 
3212   // Add the semicolon and the null
3213   dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3214   dest[dest_index] = '\0';
3215   return dest;
3216 }

3518 jint InstanceKlass::compute_modifier_flags() const {
3519   jint access = access_flags().as_int();
3520 
3521   // But check if it happens to be member class.
3522   InnerClassesIterator iter(this);
3523   for (; !iter.done(); iter.next()) {
3524     int ioff = iter.inner_class_info_index();
3525     // Inner class attribute can be zero, skip it.
3526     // Strange but true:  JVM spec. allows null inner class refs.
3527     if (ioff == 0) continue;
3528 
3529     // only look at classes that are already loaded
3530     // since we are looking for the flags for our self.
3531     Symbol* inner_name = constants()->klass_name_at(ioff);
3532     if (name() == inner_name) {
3533       // This is really a member class.
3534       access = iter.inner_access_flags();
3535       break;
3536     }
3537   }
3538   return (access & JVM_ACC_WRITTEN_FLAGS);

3539 }
3540 
3541 jint InstanceKlass::jvmti_class_status() const {
3542   jint result = 0;
3543 
3544   if (is_linked()) {
3545     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3546   }
3547 
3548   if (is_initialized()) {
3549     assert(is_linked(), "Class status is not consistent");
3550     result |= JVMTI_CLASS_STATUS_INITIALIZED;
3551   }
3552   if (is_in_error_state()) {
3553     result |= JVMTI_CLASS_STATUS_ERROR;
3554   }
3555   return result;
3556 }
3557 
3558 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {

3772     }
3773     osr = osr->osr_link();
3774   }
3775 
3776   assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
3777   if (best != nullptr && best->comp_level() >= comp_level) {
3778     return best;
3779   }
3780   return nullptr;
3781 }
3782 
3783 // -----------------------------------------------------------------------------------------------------
3784 // Printing
3785 
3786 #define BULLET  " - "
3787 
3788 static const char* state_names[] = {
3789   "allocated", "loaded", "being_linked", "linked", "being_initialized", "fully_initialized", "initialization_error"
3790 };
3791 
3792 static void print_vtable(address self, intptr_t* start, int len, outputStream* st) {
3793   ResourceMark rm;
3794   int* forward_refs = NEW_RESOURCE_ARRAY(int, len);
3795   for (int i = 0; i < len; i++)  forward_refs[i] = 0;
3796   for (int i = 0; i < len; i++) {
3797     intptr_t e = start[i];
3798     st->print("%d : " INTPTR_FORMAT, i, e);
3799     if (forward_refs[i] != 0) {
3800       int from = forward_refs[i];
3801       int off = (int) start[from];
3802       st->print(" (offset %d <= [%d])", off, from);
3803     }
3804     if (MetaspaceObj::is_valid((Metadata*)e)) {
3805       st->print(" ");
3806       ((Metadata*)e)->print_value_on(st);
3807     } else if (self != nullptr && e > 0 && e < 0x10000) {
3808       address location = self + e;
3809       int index = (int)((intptr_t*)location - start);
3810       st->print(" (offset %d => [%d])", (int)e, index);
3811       if (index >= 0 && index < len)
3812         forward_refs[index] = i;
3813     }
3814     st->cr();
3815   }
3816 }
3817 
3818 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3819   return print_vtable(nullptr, reinterpret_cast<intptr_t*>(start), len, st);
3820 }
3821 
3822 template<typename T>
3823  static void print_array_on(outputStream* st, Array<T>* array) {
3824    if (array == nullptr) { st->print_cr("nullptr"); return; }
3825    array->print_value_on(st); st->cr();
3826    if (Verbose || WizardMode) {
3827      for (int i = 0; i < array->length(); i++) {
3828        st->print("%d : ", i); array->at(i)->print_value_on(st); st->cr();
3829      }
3830    }
3831  }
3832 
3833 static void print_array_on(outputStream* st, Array<int>* array) {
3834   if (array == nullptr) { st->print_cr("nullptr"); return; }
3835   array->print_value_on(st); st->cr();
3836   if (Verbose || WizardMode) {
3837     for (int i = 0; i < array->length(); i++) {
3838       st->print("%d : %d", i, array->at(i)); st->cr();
3839     }
3840   }
3841 }
3842 
3843 const char* InstanceKlass::init_state_name() const {
3844   return state_names[init_state()];
3845 }
3846 
3847 void InstanceKlass::print_on(outputStream* st) const {
3848   assert(is_klass(), "must be klass");
3849   Klass::print_on(st);
3850 
3851   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3852   st->print(BULLET"klass size:        %d", size());                               st->cr();
3853   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
3854   st->print(BULLET"flags:             "); _misc_flags.print_on(st);               st->cr();
3855   st->print(BULLET"state:             "); st->print_cr("%s", init_state_name());
3856   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3857   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3858   st->print(BULLET"sub:               ");
3859   Klass* sub = subklass();
3860   int n;
3861   for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
3862     if (n < MaxSubklassPrintSize) {
3863       sub->print_value_on(st);
3864       st->print("   ");
3865     }
3866   }
3867   if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize);
3868   st->cr();
3869 
3870   if (is_interface()) {
3871     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
3872     if (nof_implementors() == 1) {
3873       st->print_cr(BULLET"implementor:    ");
3874       st->print("   ");
3875       implementor()->print_value_on(st);
3876       st->cr();
3877     }
3878   }
3879 
3880   st->print(BULLET"arrays:            "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3881   st->print(BULLET"methods:           "); print_array_on(st, methods());
3882   st->print(BULLET"method ordering:   "); print_array_on(st, method_ordering());
3883   st->print(BULLET"default_methods:   "); print_array_on(st, default_methods());












3884   if (default_vtable_indices() != nullptr) {
3885     st->print(BULLET"default vtable indices:   "); print_array_on(st, default_vtable_indices());
3886   }
3887   st->print(BULLET"local interfaces:  "); print_array_on(st, local_interfaces());
3888   st->print(BULLET"trans. interfaces: "); print_array_on(st, transitive_interfaces());
3889   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
3890   if (class_loader_data() != nullptr) {
3891     st->print(BULLET"class loader data:  ");
3892     class_loader_data()->print_value_on(st);
3893     st->cr();
3894   }
3895   if (source_file_name() != nullptr) {
3896     st->print(BULLET"source file:       ");
3897     source_file_name()->print_value_on(st);
3898     st->cr();
3899   }
3900   if (source_debug_extension() != nullptr) {
3901     st->print(BULLET"source debug extension:       ");
3902     st->print("%s", source_debug_extension());
3903     st->cr();
3904   }
3905   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
3906   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
3907   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
3908   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();

3914          pv_node = pv_node->previous_versions()) {
3915       if (!have_pv)
3916         st->print(BULLET"previous version:  ");
3917       have_pv = true;
3918       pv_node->constants()->print_value_on(st);
3919     }
3920     if (have_pv) st->cr();
3921   }
3922 
3923   if (generic_signature() != nullptr) {
3924     st->print(BULLET"generic signature: ");
3925     generic_signature()->print_value_on(st);
3926     st->cr();
3927   }
3928   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
3929   st->print(BULLET"nest members:     "); nest_members()->print_value_on(st);     st->cr();
3930   if (record_components() != nullptr) {
3931     st->print(BULLET"record components:     "); record_components()->print_value_on(st);     st->cr();
3932   }
3933   st->print(BULLET"permitted subclasses:     "); permitted_subclasses()->print_value_on(st);     st->cr();
3934   st->print(BULLET"preload classes:     "); preload_classes()->print_value_on(st); st->cr();
3935   if (java_mirror() != nullptr) {
3936     st->print(BULLET"java mirror:       ");
3937     java_mirror()->print_value_on(st);
3938     st->cr();
3939   } else {
3940     st->print_cr(BULLET"java mirror:       null");
3941   }
3942   st->print(BULLET"vtable length      %d  (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3943   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
3944   st->print(BULLET"itable length      %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3945   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(nullptr, start_of_itable(), itable_length(), st);
3946   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3947   FieldPrinter print_static_field(st);
3948   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3949   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3950   FieldPrinter print_nonstatic_field(st);
3951   InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3952   ik->print_nonstatic_fields(&print_nonstatic_field);
3953 
3954   st->print(BULLET"non-static oop maps: ");
3955   OopMapBlock* map     = start_of_nonstatic_oop_maps();
3956   OopMapBlock* end_map = map + nonstatic_oop_map_count();
3957   while (map < end_map) {
3958     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3959     map++;
3960   }
3961   st->cr();
3962 }
3963 
3964 void InstanceKlass::print_value_on(outputStream* st) const {
3965   assert(is_klass(), "must be klass");
< prev index next >