1 /*
   2  * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "aot/aotLoader.hpp"
  28 #include "classfile/classFileParser.hpp"
  29 #include "classfile/classFileStream.hpp"
  30 #include "classfile/classLoader.hpp"
  31 #include "classfile/classLoaderData.inline.hpp"
  32 #include "classfile/javaClasses.hpp"
  33 #include "classfile/moduleEntry.hpp"
  34 #include "classfile/symbolTable.hpp"
  35 #include "classfile/systemDictionary.hpp"
  36 #include "classfile/systemDictionaryShared.hpp"
  37 #include "classfile/verifier.hpp"
  38 #include "classfile/vmSymbols.hpp"
  39 #include "code/dependencyContext.hpp"
  40 #include "compiler/compileBroker.hpp"
  41 #include "gc/shared/collectedHeap.inline.hpp"
  42 #include "interpreter/oopMapCache.hpp"
  43 #include "interpreter/rewriter.hpp"
  44 #include "jvmtifiles/jvmti.h"
  45 #include "logging/log.hpp"
  46 #include "logging/logMessage.hpp"
  47 #include "logging/logStream.hpp"
  48 #include "memory/allocation.inline.hpp"
  49 #include "memory/heapInspection.hpp"
  50 #include "memory/iterator.inline.hpp"
  51 #include "memory/metadataFactory.hpp"
  52 #include "memory/metaspaceClosure.hpp"
  53 #include "memory/metaspaceShared.hpp"
  54 #include "memory/oopFactory.hpp"
  55 #include "memory/resourceArea.hpp"
  56 #include "memory/universe.hpp"
  57 #include "oops/fieldStreams.hpp"
  58 #include "oops/constantPool.hpp"
  59 #include "oops/instanceClassLoaderKlass.hpp"
  60 #include "oops/instanceKlass.inline.hpp"
  61 #include "oops/instanceMirrorKlass.hpp"
  62 #include "oops/instanceOop.hpp"
  63 #include "oops/klass.inline.hpp"
  64 #include "oops/method.hpp"
  65 #include "oops/oop.inline.hpp"
  66 #include "oops/symbol.hpp"
  67 #include "oops/valueKlass.hpp"
  68 #include "prims/jvmtiExport.hpp"
  69 #include "prims/jvmtiRedefineClasses.hpp"
  70 #include "prims/jvmtiThreadState.hpp"
  71 #include "prims/methodComparator.hpp"
  72 #include "runtime/atomic.hpp"
  73 #include "runtime/fieldDescriptor.inline.hpp"
  74 #include "runtime/handles.inline.hpp"
  75 #include "runtime/javaCalls.hpp"
  76 #include "runtime/mutexLocker.hpp"
  77 #include "runtime/orderAccess.hpp"
  78 #include "runtime/thread.inline.hpp"
  79 #include "services/classLoadingService.hpp"
  80 #include "services/threadService.hpp"
  81 #include "utilities/dtrace.hpp"
  82 #include "utilities/events.hpp"
  83 #include "utilities/macros.hpp"
  84 #include "utilities/stringUtils.hpp"
  85 #ifdef COMPILER1
  86 #include "c1/c1_Compiler.hpp"
  87 #endif
  88 #if INCLUDE_JFR
  89 #include "jfr/jfrEvents.hpp"
  90 #endif
  91 
  92 
  93 #ifdef DTRACE_ENABLED
  94 
  95 
  96 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
  97 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
  98 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
  99 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
 100 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
 101 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
 102 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
 103 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
 104 #define DTRACE_CLASSINIT_PROBE(type, thread_type)                \
 105   {                                                              \
 106     char* data = NULL;                                           \
 107     int len = 0;                                                 \
 108     Symbol* clss_name = name();                                  \
 109     if (clss_name != NULL) {                                     \
 110       data = (char*)clss_name->bytes();                          \
 111       len = clss_name->utf8_length();                            \
 112     }                                                            \
 113     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
 114       data, len, (void*)class_loader(), thread_type);            \
 115   }
 116 
 117 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)     \
 118   {                                                              \
 119     char* data = NULL;                                           \
 120     int len = 0;                                                 \
 121     Symbol* clss_name = name();                                  \
 122     if (clss_name != NULL) {                                     \
 123       data = (char*)clss_name->bytes();                          \
 124       len = clss_name->utf8_length();                            \
 125     }                                                            \
 126     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
 127       data, len, (void*)class_loader(), thread_type, wait);      \
 128   }
 129 
 130 #else //  ndef DTRACE_ENABLED
 131 
 132 #define DTRACE_CLASSINIT_PROBE(type, thread_type)
 133 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)
 134 
 135 #endif //  ndef DTRACE_ENABLED
 136 
 137 static inline bool is_class_loader(const Symbol* class_name,
 138                                    const ClassFileParser& parser) {
 139   assert(class_name != NULL, "invariant");
 140 
 141   if (class_name == vmSymbols::java_lang_ClassLoader()) {
 142     return true;
 143   }
 144 
 145   if (SystemDictionary::ClassLoader_klass_loaded()) {
 146     const Klass* const super_klass = parser.super_klass();
 147     if (super_klass != NULL) {
 148       if (super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass())) {
 149         return true;
 150       }
 151     }
 152   }
 153   return false;
 154 }
 155 
 156 // called to verify that k is a member of this nest
 157 bool InstanceKlass::has_nest_member(InstanceKlass* k, TRAPS) const {
 158   if (_nest_members == NULL || _nest_members == Universe::the_empty_short_array()) {
 159     if (log_is_enabled(Trace, class, nestmates)) {
 160       ResourceMark rm(THREAD);
 161       log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
 162                                   k->external_name(), this->external_name());
 163     }
 164     return false;
 165   }
 166 
 167   if (log_is_enabled(Trace, class, nestmates)) {
 168     ResourceMark rm(THREAD);
 169     log_trace(class, nestmates)("Checking nest membership of %s in %s",
 170                                 k->external_name(), this->external_name());
 171   }
 172 
 173   // Check for a resolved cp entry , else fall back to a name check.
 174   // We don't want to resolve any class other than the one being checked.
 175   for (int i = 0; i < _nest_members->length(); i++) {
 176     int cp_index = _nest_members->at(i);
 177     if (_constants->tag_at(cp_index).is_klass()) {
 178       Klass* k2 = _constants->klass_at(cp_index, CHECK_false);
 179       if (k2 == k) {
 180         log_trace(class, nestmates)("- class is listed at nest_members[%d] => cp[%d]", i, cp_index);
 181         return true;
 182       }
 183     }
 184     else {
 185       Symbol* name = _constants->klass_name_at(cp_index);
 186       if (name == k->name()) {
 187         log_trace(class, nestmates)("- Found it at nest_members[%d] => cp[%d]", i, cp_index);
 188 
 189         // Names match so check actual klass - this may trigger class loading if
 190         // it doesn't match (though that should be impossible). But to be safe we
 191         // have to check for a compiler thread executing here.
 192         if (!THREAD->can_call_java() && !_constants->tag_at(cp_index).is_klass()) {
 193           log_trace(class, nestmates)("- validation required resolution in an unsuitable thread");
 194           return false;
 195         }
 196 
 197         Klass* k2 = _constants->klass_at(cp_index, CHECK_false);
 198         if (k2 == k) {
 199           log_trace(class, nestmates)("- class is listed as a nest member");
 200           return true;
 201         }
 202         else {
 203           // same name but different klass!
 204           log_trace(class, nestmates)(" - klass comparison failed!");
 205           // can't have two names the same, so we're done
 206           return false;
 207         }
 208       }
 209     }
 210   }
 211   log_trace(class, nestmates)("- class is NOT a nest member!");
 212   return false;
 213 }
 214 
 215 // Return nest-host class, resolving, validating and saving it if needed.
 216 // In cases where this is called from a thread that can not do classloading
 217 // (such as a native JIT thread) then we simply return NULL, which in turn
 218 // causes the access check to return false. Such code will retry the access
 219 // from a more suitable environment later.
 220 InstanceKlass* InstanceKlass::nest_host(Symbol* validationException, TRAPS) {
 221   InstanceKlass* nest_host_k = _nest_host;
 222   if (nest_host_k == NULL) {
 223     // need to resolve and save our nest-host class. This could be attempted
 224     // concurrently but as the result is idempotent and we don't use the class
 225     // then we do not need any synchronization beyond what is implicitly used
 226     // during class loading.
 227     if (_nest_host_index != 0) { // we have a real nest_host
 228       // Before trying to resolve check if we're in a suitable context
 229       if (!THREAD->can_call_java() && !_constants->tag_at(_nest_host_index).is_klass()) {
 230         if (log_is_enabled(Trace, class, nestmates)) {
 231           ResourceMark rm(THREAD);
 232           log_trace(class, nestmates)("Rejected resolution of nest-host of %s in unsuitable thread",
 233                                       this->external_name());
 234         }
 235         return NULL;
 236       }
 237 
 238       if (log_is_enabled(Trace, class, nestmates)) {
 239         ResourceMark rm(THREAD);
 240         log_trace(class, nestmates)("Resolving nest-host of %s using cp entry for %s",
 241                                     this->external_name(),
 242                                     _constants->klass_name_at(_nest_host_index)->as_C_string());
 243       }
 244 
 245       Klass* k = _constants->klass_at(_nest_host_index, THREAD);
 246       if (HAS_PENDING_EXCEPTION) {
 247         Handle exc_h = Handle(THREAD, PENDING_EXCEPTION);
 248         if (exc_h->is_a(SystemDictionary::NoClassDefFoundError_klass())) {
 249           // throw a new CDNFE with the original as its cause, and a clear msg
 250           ResourceMark rm(THREAD);
 251           char buf[200];
 252           CLEAR_PENDING_EXCEPTION;
 253           jio_snprintf(buf, sizeof(buf),
 254                        "Unable to load nest-host class (%s) of %s",
 255                        _constants->klass_name_at(_nest_host_index)->as_C_string(),
 256                        this->external_name());
 257           log_trace(class, nestmates)("%s - NoClassDefFoundError", buf);
 258           THROW_MSG_CAUSE_NULL(vmSymbols::java_lang_NoClassDefFoundError(), buf, exc_h);
 259         }
 260         // All other exceptions pass through (OOME, StackOverflowError, LinkageErrors etc).
 261         return NULL;
 262       }
 263 
 264       // A valid nest-host is an instance class in the current package that lists this
 265       // class as a nest member. If any of these conditions are not met we post the
 266       // requested exception type (if any) and return NULL
 267 
 268       const char* error = NULL;
 269 
 270       // JVMS 5.4.4 indicates package check comes first
 271       if (is_same_class_package(k)) {
 272 
 273         // Now check actual membership. We can't be a member if our "host" is
 274         // not an instance class.
 275         if (k->is_instance_klass()) {
 276           nest_host_k = InstanceKlass::cast(k);
 277 
 278           bool is_member = nest_host_k->has_nest_member(this, CHECK_NULL);
 279           if (is_member) {
 280             // save resolved nest-host value
 281             _nest_host = nest_host_k;
 282 
 283             if (log_is_enabled(Trace, class, nestmates)) {
 284               ResourceMark rm(THREAD);
 285               log_trace(class, nestmates)("Resolved nest-host of %s to %s",
 286                                           this->external_name(), k->external_name());
 287             }
 288             return nest_host_k;
 289           }
 290         }
 291         error = "current type is not listed as a nest member";
 292       } else {
 293         error = "types are in different packages";
 294       }
 295 
 296       if (log_is_enabled(Trace, class, nestmates)) {
 297         ResourceMark rm(THREAD);
 298         log_trace(class, nestmates)
 299           ("Type %s (loader: %s) is not a nest member of "
 300            "resolved type %s (loader: %s): %s",
 301            this->external_name(),
 302            this->class_loader_data()->loader_name_and_id(),
 303            k->external_name(),
 304            k->class_loader_data()->loader_name_and_id(),
 305            error);
 306       }
 307 
 308       if (validationException != NULL && THREAD->can_call_java()) {
 309         ResourceMark rm(THREAD);
 310         Exceptions::fthrow(THREAD_AND_LOCATION,
 311                            validationException,
 312                            "Type %s (loader: %s) is not a nest member of %s (loader: %s): %s",
 313                            this->external_name(),
 314                            this->class_loader_data()->loader_name_and_id(),
 315                            k->external_name(),
 316                            k->class_loader_data()->loader_name_and_id(),
 317                            error
 318                            );
 319       }
 320       return NULL;
 321     } else {
 322       if (log_is_enabled(Trace, class, nestmates)) {
 323         ResourceMark rm(THREAD);
 324         log_trace(class, nestmates)("Type %s is not part of a nest: setting nest-host to self",
 325                                     this->external_name());
 326       }
 327       // save resolved nest-host value
 328       return (_nest_host = this);
 329     }
 330   }
 331   return nest_host_k;
 332 }
 333 
 334 // check if 'this' and k are nestmates (same nest_host), or k is our nest_host,
 335 // or we are k's nest_host - all of which is covered by comparing the two
 336 // resolved_nest_hosts
 337 bool InstanceKlass::has_nestmate_access_to(InstanceKlass* k, TRAPS) {
 338 
 339   assert(this != k, "this should be handled by higher-level code");
 340 
 341   // Per JVMS 5.4.4 we first resolve and validate the current class, then
 342   // the target class k. Resolution exceptions will be passed on by upper
 343   // layers. IncompatibleClassChangeErrors from membership validation failures
 344   // will also be passed through.
 345 
 346   Symbol* icce = vmSymbols::java_lang_IncompatibleClassChangeError();
 347   InstanceKlass* cur_host = nest_host(icce, CHECK_false);
 348   if (cur_host == NULL) {
 349     return false;
 350   }
 351 
 352   Klass* k_nest_host = k->nest_host(icce, CHECK_false);
 353   if (k_nest_host == NULL) {
 354     return false;
 355   }
 356 
 357   bool access = (cur_host == k_nest_host);
 358 
 359   if (log_is_enabled(Trace, class, nestmates)) {
 360     ResourceMark rm(THREAD);
 361     log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
 362                                 this->external_name(),
 363                                 access ? "" : "NOT ",
 364                                 k->external_name());
 365   }
 366 
 367   return access;
 368 }
 369 
 370 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
 371   const int size = InstanceKlass::size(parser.vtable_size(),
 372                                        parser.itable_size(),
 373                                        nonstatic_oop_map_size(parser.total_oop_map_count()),
 374                                        parser.is_interface(),
 375                                        parser.is_unsafe_anonymous(),
 376                                        should_store_fingerprint(parser.is_unsafe_anonymous()),
 377                                        parser.has_flattenable_fields() ? parser.java_fields_count() : 0,
 378                                        parser.is_value_type());
 379 
 380   const Symbol* const class_name = parser.class_name();
 381   assert(class_name != NULL, "invariant");
 382   ClassLoaderData* loader_data = parser.loader_data();
 383   assert(loader_data != NULL, "invariant");
 384 
 385   InstanceKlass* ik;
 386 
 387   // Allocation
 388   if (REF_NONE == parser.reference_type()) {
 389     if (class_name == vmSymbols::java_lang_Class()) {
 390       // mirror
 391       ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
 392     } else if (is_class_loader(class_name, parser)) {
 393       // class loader
 394       ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);
 395     } else if (parser.is_value_type()) {
 396       // value type
 397       ik = new (loader_data, size, THREAD) ValueKlass(parser);
 398     } else {
 399       // normal
 400       ik = new (loader_data, size, THREAD) InstanceKlass(parser, InstanceKlass::_misc_kind_other);
 401     }
 402   } else {
 403     // reference
 404     ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
 405   }
 406 
 407   // Check for pending exception before adding to the loader data and incrementing
 408   // class count.  Can get OOM here.
 409   if (HAS_PENDING_EXCEPTION) {
 410     return NULL;
 411   }
 412 
 413 #ifdef ASSERT
 414   assert(ik->size() == size, "");
 415   ik->bounds_check((address) ik->start_of_vtable(), false, size);
 416   ik->bounds_check((address) ik->start_of_itable(), false, size);
 417   ik->bounds_check((address) ik->end_of_itable(), true, size);
 418   ik->bounds_check((address) ik->end_of_nonstatic_oop_maps(), true, size);
 419 #endif //ASSERT
 420   return ik;
 421 }
 422 
 423 #ifndef PRODUCT
 424 bool InstanceKlass::bounds_check(address addr, bool edge_ok, intptr_t size_in_bytes) const {
 425   const char* bad = NULL;
 426   address end = NULL;
 427   if (addr < (address)this) {
 428     bad = "before";
 429   } else if (addr == (address)this) {
 430     if (edge_ok)  return true;
 431     bad = "just before";
 432   } else if (addr == (end = (address)this + sizeof(intptr_t) * (size_in_bytes < 0 ? size() : size_in_bytes))) {
 433     if (edge_ok)  return true;
 434     bad = "just after";
 435   } else if (addr > end) {
 436     bad = "after";
 437   } else {
 438     return true;
 439   }
 440   tty->print_cr("%s object bounds: " INTPTR_FORMAT " [" INTPTR_FORMAT ".." INTPTR_FORMAT "]",
 441       bad, (intptr_t)addr, (intptr_t)this, (intptr_t)end);
 442   Verbose = WizardMode = true; this->print(); //@@
 443   return false;
 444 }
 445 #endif //PRODUCT
 446 
 447 // copy method ordering from resource area to Metaspace
 448 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
 449   if (m != NULL) {
 450     // allocate a new array and copy contents (memcpy?)
 451     _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
 452     for (int i = 0; i < m->length(); i++) {
 453       _method_ordering->at_put(i, m->at(i));
 454     }
 455   } else {
 456     _method_ordering = Universe::the_empty_int_array();
 457   }
 458 }
 459 
 460 // create a new array of vtable_indices for default methods
 461 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
 462   Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
 463   assert(default_vtable_indices() == NULL, "only create once");
 464   set_default_vtable_indices(vtable_indices);
 465   return vtable_indices;
 466 }
 467 
 468 InstanceKlass::InstanceKlass(const ClassFileParser& parser, unsigned kind, KlassID id) :
 469   Klass(id),
 470   _nest_members(NULL),
 471   _nest_host_index(0),
 472   _nest_host(NULL),
 473   _static_field_size(parser.static_field_size()),
 474   _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
 475   _itable_len(parser.itable_size()),
 476   _extra_flags(0),
 477   _init_thread(NULL),
 478   _init_state(allocated),
 479   _reference_type(parser.reference_type()),
 480   _adr_valueklass_fixed_block(NULL)
 481 {
 482   set_vtable_length(parser.vtable_size());
 483   set_kind(kind);
 484   set_access_flags(parser.access_flags());
 485   set_is_unsafe_anonymous(parser.is_unsafe_anonymous());
 486   set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
 487                                                     false));
 488     if (parser.has_flattenable_fields()) {
 489       set_has_value_fields();
 490     }
 491     _java_fields_count = parser.java_fields_count();
 492 
 493     assert(NULL == _methods, "underlying memory not zeroed?");
 494     assert(is_instance_klass(), "is layout incorrect?");
 495     assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
 496 
 497   if (DumpSharedSpaces || DynamicDumpSharedSpaces) {
 498       SystemDictionaryShared::init_dumptime_info(this);
 499     }
 500 }
 501 
 502 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
 503                                        Array<Method*>* methods) {
 504   if (methods != NULL && methods != Universe::the_empty_method_array() &&
 505       !methods->is_shared()) {
 506     for (int i = 0; i < methods->length(); i++) {
 507       Method* method = methods->at(i);
 508       if (method == NULL) continue;  // maybe null if error processing
 509       // Only want to delete methods that are not executing for RedefineClasses.
 510       // The previous version will point to them so they're not totally dangling
 511       assert (!method->on_stack(), "shouldn't be called with methods on stack");
 512       MetadataFactory::free_metadata(loader_data, method);
 513     }
 514     MetadataFactory::free_array<Method*>(loader_data, methods);
 515   }
 516 }
 517 
 518 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
 519                                           const Klass* super_klass,
 520                                           Array<InstanceKlass*>* local_interfaces,
 521                                           Array<InstanceKlass*>* transitive_interfaces) {
 522   // Only deallocate transitive interfaces if not empty, same as super class
 523   // or same as local interfaces.  See code in parseClassFile.
 524   Array<InstanceKlass*>* ti = transitive_interfaces;
 525   if (ti != Universe::the_empty_instance_klass_array() && ti != local_interfaces) {
 526     // check that the interfaces don't come from super class
 527     Array<InstanceKlass*>* sti = (super_klass == NULL) ? NULL :
 528                     InstanceKlass::cast(super_klass)->transitive_interfaces();
 529     if (ti != sti && ti != NULL && !ti->is_shared()) {
 530       MetadataFactory::free_array<InstanceKlass*>(loader_data, ti);
 531     }
 532   }
 533 
 534   // local interfaces can be empty
 535   if (local_interfaces != Universe::the_empty_instance_klass_array() &&
 536       local_interfaces != NULL && !local_interfaces->is_shared()) {
 537     MetadataFactory::free_array<InstanceKlass*>(loader_data, local_interfaces);
 538   }
 539 }
 540 
 541 // This function deallocates the metadata and C heap pointers that the
 542 // InstanceKlass points to.
 543 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
 544 
 545   // Orphan the mirror first, CMS thinks it's still live.
 546   if (java_mirror() != NULL) {
 547     java_lang_Class::set_klass(java_mirror(), NULL);
 548   }
 549 
 550   // Also remove mirror from handles
 551   loader_data->remove_handle(_java_mirror);
 552 
 553   // Need to take this class off the class loader data list.
 554   loader_data->remove_class(this);
 555 
 556   // The array_klass for this class is created later, after error handling.
 557   // For class redefinition, we keep the original class so this scratch class
 558   // doesn't have an array class.  Either way, assert that there is nothing
 559   // to deallocate.
 560   assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
 561 
 562   // Release C heap allocated data that this might point to, which includes
 563   // reference counting symbol names.
 564   release_C_heap_structures();
 565 
 566   deallocate_methods(loader_data, methods());
 567   set_methods(NULL);
 568 
 569   if (method_ordering() != NULL &&
 570       method_ordering() != Universe::the_empty_int_array() &&
 571       !method_ordering()->is_shared()) {
 572     MetadataFactory::free_array<int>(loader_data, method_ordering());
 573   }
 574   set_method_ordering(NULL);
 575 
 576   // default methods can be empty
 577   if (default_methods() != NULL &&
 578       default_methods() != Universe::the_empty_method_array() &&
 579       !default_methods()->is_shared()) {
 580     MetadataFactory::free_array<Method*>(loader_data, default_methods());
 581   }
 582   // Do NOT deallocate the default methods, they are owned by superinterfaces.
 583   set_default_methods(NULL);
 584 
 585   // default methods vtable indices can be empty
 586   if (default_vtable_indices() != NULL &&
 587       !default_vtable_indices()->is_shared()) {
 588     MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
 589   }
 590   set_default_vtable_indices(NULL);
 591 
 592 
 593   // This array is in Klass, but remove it with the InstanceKlass since
 594   // this place would be the only caller and it can share memory with transitive
 595   // interfaces.
 596   if (secondary_supers() != NULL &&
 597       secondary_supers() != Universe::the_empty_klass_array() &&
 598       // see comments in compute_secondary_supers about the following cast
 599       (address)(secondary_supers()) != (address)(transitive_interfaces()) &&
 600       !secondary_supers()->is_shared()) {
 601     MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
 602   }
 603   set_secondary_supers(NULL);
 604 
 605   deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
 606   set_transitive_interfaces(NULL);
 607   set_local_interfaces(NULL);
 608 
 609   if (fields() != NULL && !fields()->is_shared()) {
 610     MetadataFactory::free_array<jushort>(loader_data, fields());
 611   }
 612   set_fields(NULL, 0);
 613 
 614   // If a method from a redefined class is using this constant pool, don't
 615   // delete it, yet.  The new class's previous version will point to this.
 616   if (constants() != NULL) {
 617     assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
 618     if (!constants()->is_shared()) {
 619       MetadataFactory::free_metadata(loader_data, constants());
 620     }
 621     // Delete any cached resolution errors for the constant pool
 622     SystemDictionary::delete_resolution_error(constants());
 623 
 624     set_constants(NULL);
 625   }
 626 
 627   if (inner_classes() != NULL &&
 628       inner_classes() != Universe::the_empty_short_array() &&
 629       !inner_classes()->is_shared()) {
 630     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
 631   }
 632   set_inner_classes(NULL);
 633 
 634   if (nest_members() != NULL &&
 635       nest_members() != Universe::the_empty_short_array() &&
 636       !nest_members()->is_shared()) {
 637     MetadataFactory::free_array<jushort>(loader_data, nest_members());
 638   }
 639   set_nest_members(NULL);
 640 
 641   // We should deallocate the Annotations instance if it's not in shared spaces.
 642   if (annotations() != NULL && !annotations()->is_shared()) {
 643     MetadataFactory::free_metadata(loader_data, annotations());
 644   }
 645   set_annotations(NULL);
 646 
 647   if (DumpSharedSpaces || DynamicDumpSharedSpaces) {
 648     SystemDictionaryShared::remove_dumptime_info(this);
 649   }
 650 }
 651 
 652 bool InstanceKlass::should_be_initialized() const {
 653   return !is_initialized();
 654 }
 655 
 656 klassItable InstanceKlass::itable() const {
 657   return klassItable(const_cast<InstanceKlass*>(this));
 658 }
 659 
 660 void InstanceKlass::eager_initialize(Thread *thread) {
 661   if (!EagerInitialization) return;
 662 
 663   if (this->is_not_initialized()) {
 664     // abort if the the class has a class initializer
 665     if (this->class_initializer() != NULL) return;
 666 
 667     // abort if it is java.lang.Object (initialization is handled in genesis)
 668     Klass* super_klass = super();
 669     if (super_klass == NULL) return;
 670 
 671     // abort if the super class should be initialized
 672     if (!InstanceKlass::cast(super_klass)->is_initialized()) return;
 673 
 674     // call body to expose the this pointer
 675     eager_initialize_impl();
 676   }
 677 }
 678 
 679 // JVMTI spec thinks there are signers and protection domain in the
 680 // instanceKlass.  These accessors pretend these fields are there.
 681 // The hprof specification also thinks these fields are in InstanceKlass.
 682 oop InstanceKlass::protection_domain() const {
 683   // return the protection_domain from the mirror
 684   return java_lang_Class::protection_domain(java_mirror());
 685 }
 686 
 687 // To remove these from requires an incompatible change and CCC request.
 688 objArrayOop InstanceKlass::signers() const {
 689   // return the signers from the mirror
 690   return java_lang_Class::signers(java_mirror());
 691 }
 692 
 693 oop InstanceKlass::init_lock() const {
 694   // return the init lock from the mirror
 695   oop lock = java_lang_Class::init_lock(java_mirror());
 696   // Prevent reordering with any access of initialization state
 697   OrderAccess::loadload();
 698   assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state
 699          "only fully initialized state can have a null lock");
 700   return lock;
 701 }
 702 
 703 // Set the initialization lock to null so the object can be GC'ed.  Any racing
 704 // threads to get this lock will see a null lock and will not lock.
 705 // That's okay because they all check for initialized state after getting
 706 // the lock and return.
 707 void InstanceKlass::fence_and_clear_init_lock() {
 708   // make sure previous stores are all done, notably the init_state.
 709   OrderAccess::storestore();
 710   java_lang_Class::set_init_lock(java_mirror(), NULL);
 711   assert(!is_not_initialized(), "class must be initialized now");
 712 }
 713 
 714 void InstanceKlass::eager_initialize_impl() {
 715   EXCEPTION_MARK;
 716   HandleMark hm(THREAD);
 717   Handle h_init_lock(THREAD, init_lock());
 718   ObjectLocker ol(h_init_lock, THREAD, h_init_lock() != NULL);
 719 
 720   // abort if someone beat us to the initialization
 721   if (!is_not_initialized()) return;  // note: not equivalent to is_initialized()
 722 
 723   ClassState old_state = init_state();
 724   link_class_impl(THREAD);
 725   if (HAS_PENDING_EXCEPTION) {
 726     CLEAR_PENDING_EXCEPTION;
 727     // Abort if linking the class throws an exception.
 728 
 729     // Use a test to avoid redundantly resetting the state if there's
 730     // no change.  Set_init_state() asserts that state changes make
 731     // progress, whereas here we might just be spinning in place.
 732     if (old_state != _init_state)
 733       set_init_state(old_state);
 734   } else {
 735     // linking successfull, mark class as initialized
 736     set_init_state(fully_initialized);
 737     fence_and_clear_init_lock();
 738     // trace
 739     if (log_is_enabled(Info, class, init)) {
 740       ResourceMark rm(THREAD);
 741       log_info(class, init)("[Initialized %s without side effects]", external_name());
 742     }
 743   }
 744 }
 745 
 746 
 747 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
 748 // process. The step comments refers to the procedure described in that section.
 749 // Note: implementation moved to static method to expose the this pointer.
 750 void InstanceKlass::initialize(TRAPS) {
 751   if (this->should_be_initialized()) {
 752     initialize_impl(CHECK);
 753     // Note: at this point the class may be initialized
 754     //       OR it may be in the state of being initialized
 755     //       in case of recursive initialization!
 756   } else {
 757     assert(is_initialized(), "sanity check");
 758   }
 759 }
 760 
 761 
 762 bool InstanceKlass::verify_code(TRAPS) {
 763   // 1) Verify the bytecodes
 764   return Verifier::verify(this, should_verify_class(), THREAD);
 765 }
 766 
 767 void InstanceKlass::link_class(TRAPS) {
 768   assert(is_loaded(), "must be loaded");
 769   if (!is_linked()) {
 770     link_class_impl(CHECK);
 771   }
 772 }
 773 
 774 // Called to verify that a class can link during initialization, without
 775 // throwing a VerifyError.
 776 bool InstanceKlass::link_class_or_fail(TRAPS) {
 777   assert(is_loaded(), "must be loaded");
 778   if (!is_linked()) {
 779     link_class_impl(CHECK_false);
 780   }
 781   return is_linked();
 782 }
 783 
 784 bool InstanceKlass::link_class_impl(TRAPS) {
 785   if (DumpSharedSpaces && is_in_error_state()) {
 786     // This is for CDS dumping phase only -- we use the in_error_state to indicate that
 787     // the class has failed verification. Throwing the NoClassDefFoundError here is just
 788     // a convenient way to stop repeat attempts to verify the same (bad) class.
 789     //
 790     // Note that the NoClassDefFoundError is not part of the JLS, and should not be thrown
 791     // if we are executing Java code. This is not a problem for CDS dumping phase since
 792     // it doesn't execute any Java code.
 793     ResourceMark rm(THREAD);
 794     Exceptions::fthrow(THREAD_AND_LOCATION,
 795                        vmSymbols::java_lang_NoClassDefFoundError(),
 796                        "Class %s, or one of its supertypes, failed class initialization",
 797                        external_name());
 798     return false;
 799   }
 800   // return if already verified
 801   if (is_linked()) {
 802     return true;
 803   }
 804 
 805   // Timing
 806   // timer handles recursion
 807   assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
 808   JavaThread* jt = (JavaThread*)THREAD;
 809 
 810   // link super class before linking this class
 811   Klass* super_klass = super();
 812   if (super_klass != NULL) {
 813     if (super_klass->is_interface()) {  // check if super class is an interface
 814       ResourceMark rm(THREAD);
 815       Exceptions::fthrow(
 816         THREAD_AND_LOCATION,
 817         vmSymbols::java_lang_IncompatibleClassChangeError(),
 818         "class %s has interface %s as super class",
 819         external_name(),
 820         super_klass->external_name()
 821       );
 822       return false;
 823     }
 824 
 825     InstanceKlass* ik_super = InstanceKlass::cast(super_klass);
 826     ik_super->link_class_impl(CHECK_false);
 827   }
 828 
 829   // link all interfaces implemented by this class before linking this class
 830   Array<InstanceKlass*>* interfaces = local_interfaces();
 831   int num_interfaces = interfaces->length();
 832   for (int index = 0; index < num_interfaces; index++) {
 833     InstanceKlass* interk = interfaces->at(index);
 834     interk->link_class_impl(CHECK_false);
 835   }
 836 
 837 
 838   // If a class declares a method that uses a value class as an argument
 839   // type or return value type, this value class must be loaded during the
 840   // linking of this class because size and properties of the value class
 841   // must be known in order to be able to perform value type optimizations.
 842   // The implementation below is an approximation of this rule, the code
 843   // iterates over all methods of the current class (including overridden
 844   // methods), not only the methods declared by this class. This
 845   // approximation makes the code simpler, and doesn't change the semantic
 846   // because classes declaring methods overridden by the current class are
 847   // linked (and have performed their own pre-loading) before the linking
 848   // of the current class.
 849   // This is also the moment to detect potential mismatch between the
 850   // ValueTypes attribute and the kind of the class effectively loaded.
 851 
 852 
 853   // Note:
 854   // Value class types used for flattenable fields are loaded during
 855   // the loading phase (see ClassFileParser::post_process_parsed_stream()).
 856   // Value class types used as element types for array creation
 857   // are not pre-loaded. Their loading is triggered by either anewarray
 858   // or multianewarray bytecodes.
 859 
 860   // Could it be possible to do the following processing only if the
 861   // class uses value types?
 862   {
 863     ResourceMark rm(THREAD);
 864     for (int i = 0; i < methods()->length(); i++) {
 865       Method* m = methods()->at(i);
 866       for (SignatureStream ss(m->signature()); !ss.is_done(); ss.next()) {
 867         Symbol* sig = ss.as_symbol();
 868         if (ss.is_object()) {
 869           Symbol* symb = sig;
 870           if (ss.is_array()) {
 871             int i=0;
 872             while (sig->char_at(i) == '[') i++;
 873             if (i == sig->utf8_length() - 1 ) continue; // primitive array
 874             symb = SymbolTable::new_symbol(sig->as_C_string() + i + 1,
 875                                            sig->utf8_length() - 3);
 876           }
 877           if (ss.type() == T_VALUETYPE) {
 878             oop loader = class_loader();
 879             oop protection_domain = this->protection_domain();
 880             Klass* klass = SystemDictionary::resolve_or_fail(symb,
 881                                                              Handle(THREAD, loader), Handle(THREAD, protection_domain), true,
 882                                                              CHECK_false);
 883             if (symb != sig) {
 884               symb->decrement_refcount();
 885             }
 886             if (klass == NULL) {
 887               THROW_(vmSymbols::java_lang_LinkageError(), false);
 888             }
 889             if (!klass->is_value()) {
 890               THROW_(vmSymbols::java_lang_IncompatibleClassChangeError(), false);
 891             }
 892           }
 893         }
 894       }
 895     }
 896   }
 897 
 898   // in case the class is linked in the process of linking its superclasses
 899   if (is_linked()) {
 900     return true;
 901   }
 902 
 903   // trace only the link time for this klass that includes
 904   // the verification time
 905   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
 906                              ClassLoader::perf_class_link_selftime(),
 907                              ClassLoader::perf_classes_linked(),
 908                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 909                              jt->get_thread_stat()->perf_timers_addr(),
 910                              PerfClassTraceTime::CLASS_LINK);
 911 
 912   // verification & rewriting
 913   {
 914     HandleMark hm(THREAD);
 915     Handle h_init_lock(THREAD, init_lock());
 916     ObjectLocker ol(h_init_lock, THREAD, h_init_lock() != NULL);
 917     // rewritten will have been set if loader constraint error found
 918     // on an earlier link attempt
 919     // don't verify or rewrite if already rewritten
 920     //
 921 
 922     if (!is_linked()) {
 923       if (!is_rewritten()) {
 924         {
 925           bool verify_ok = verify_code(THREAD);
 926           if (!verify_ok) {
 927             return false;
 928           }
 929         }
 930 
 931         // Just in case a side-effect of verify linked this class already
 932         // (which can sometimes happen since the verifier loads classes
 933         // using custom class loaders, which are free to initialize things)
 934         if (is_linked()) {
 935           return true;
 936         }
 937 
 938         // also sets rewritten
 939         rewrite_class(CHECK_false);
 940       } else if (is_shared()) {
 941         SystemDictionaryShared::check_verification_constraints(this, CHECK_false);
 942       }
 943 
 944       // relocate jsrs and link methods after they are all rewritten
 945       link_methods(CHECK_false);
 946 
 947       // Initialize the vtable and interface table after
 948       // methods have been rewritten since rewrite may
 949       // fabricate new Method*s.
 950       // also does loader constraint checking
 951       //
 952       // initialize_vtable and initialize_itable need to be rerun for
 953       // a shared class if the class is not loaded by the NULL classloader.
 954       ClassLoaderData * loader_data = class_loader_data();
 955       if (!(is_shared() &&
 956             loader_data->is_the_null_class_loader_data())) {
 957         vtable().initialize_vtable(true, CHECK_false);
 958         itable().initialize_itable(true, CHECK_false);
 959       }
 960 #ifdef ASSERT
 961       else {
 962         vtable().verify(tty, true);
 963         // In case itable verification is ever added.
 964         // itable().verify(tty, true);
 965       }
 966 #endif
 967 
 968       set_init_state(linked);
 969       if (JvmtiExport::should_post_class_prepare()) {
 970         Thread *thread = THREAD;
 971         assert(thread->is_Java_thread(), "thread->is_Java_thread()");
 972         JvmtiExport::post_class_prepare((JavaThread *) thread, this);
 973       }
 974     }
 975   }
 976   return true;
 977 }
 978 
 979 // Rewrite the byte codes of all of the methods of a class.
 980 // The rewriter must be called exactly once. Rewriting must happen after
 981 // verification but before the first method of the class is executed.
 982 void InstanceKlass::rewrite_class(TRAPS) {
 983   assert(is_loaded(), "must be loaded");
 984   if (is_rewritten()) {
 985     assert(is_shared(), "rewriting an unshared class?");
 986     return;
 987   }
 988   Rewriter::rewrite(this, CHECK);
 989   set_rewritten();
 990 }
 991 
 992 // Now relocate and link method entry points after class is rewritten.
 993 // This is outside is_rewritten flag. In case of an exception, it can be
 994 // executed more than once.
 995 void InstanceKlass::link_methods(TRAPS) {
 996   int len = methods()->length();
 997   for (int i = len-1; i >= 0; i--) {
 998     methodHandle m(THREAD, methods()->at(i));
 999 
1000     // Set up method entry points for compiler and interpreter    .
1001     m->link_method(m, CHECK);
1002   }
1003 }
1004 
1005 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
1006 void InstanceKlass::initialize_super_interfaces(TRAPS) {
1007   assert (has_nonstatic_concrete_methods(), "caller should have checked this");
1008   for (int i = 0; i < local_interfaces()->length(); ++i) {
1009     InstanceKlass* ik = local_interfaces()->at(i);
1010 
1011     // Initialization is depth first search ie. we start with top of the inheritance tree
1012     // has_nonstatic_concrete_methods drives searching superinterfaces since it
1013     // means has_nonstatic_concrete_methods in its superinterface hierarchy
1014     if (ik->has_nonstatic_concrete_methods()) {
1015       ik->initialize_super_interfaces(CHECK);
1016     }
1017 
1018     // Only initialize() interfaces that "declare" concrete methods.
1019     if (ik->should_be_initialized() && ik->declares_nonstatic_concrete_methods()) {
1020       ik->initialize(CHECK);
1021     }
1022   }
1023 }
1024 
1025 void InstanceKlass::initialize_impl(TRAPS) {
1026   HandleMark hm(THREAD);
1027 
1028   // Make sure klass is linked (verified) before initialization
1029   // A class could already be verified, since it has been reflected upon.
1030   link_class(CHECK);
1031 
1032   DTRACE_CLASSINIT_PROBE(required, -1);
1033 
1034   bool wait = false;
1035 
1036   assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
1037   JavaThread* jt = (JavaThread*)THREAD;
1038 
1039   // refer to the JVM book page 47 for description of steps
1040   // Step 1
1041   {
1042     Handle h_init_lock(THREAD, init_lock());
1043     ObjectLocker ol(h_init_lock, THREAD, h_init_lock() != NULL);
1044 
1045     // Step 2
1046     // If we were to use wait() instead of waitInterruptibly() then
1047     // we might end up throwing IE from link/symbol resolution sites
1048     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
1049     while (is_being_initialized() && !is_reentrant_initialization(jt)) {
1050       wait = true;
1051       jt->set_class_to_be_initialized(this);
1052       ol.wait_uninterruptibly(jt);
1053       jt->set_class_to_be_initialized(NULL);
1054     }
1055 
1056     // Step 3
1057     if (is_being_initialized() && is_reentrant_initialization(jt)) {
1058       DTRACE_CLASSINIT_PROBE_WAIT(recursive, -1, wait);
1059       return;
1060     }
1061 
1062     // Step 4
1063     if (is_initialized()) {
1064       DTRACE_CLASSINIT_PROBE_WAIT(concurrent, -1, wait);
1065       return;
1066     }
1067 
1068     // Step 5
1069     if (is_in_error_state()) {
1070       DTRACE_CLASSINIT_PROBE_WAIT(erroneous, -1, wait);
1071       ResourceMark rm(THREAD);
1072       const char* desc = "Could not initialize class ";
1073       const char* className = external_name();
1074       size_t msglen = strlen(desc) + strlen(className) + 1;
1075       char* message = NEW_RESOURCE_ARRAY(char, msglen);
1076       if (NULL == message) {
1077         // Out of memory: can't create detailed error message
1078           THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
1079       } else {
1080         jio_snprintf(message, msglen, "%s%s", desc, className);
1081           THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
1082       }
1083     }
1084 
1085     // Step 6
1086     set_init_state(being_initialized);
1087     set_init_thread(jt);
1088   }
1089 
1090   // Step 7
1091   // Next, if C is a class rather than an interface, initialize it's super class and super
1092   // interfaces.
1093   if (!is_interface()) {
1094     Klass* super_klass = super();
1095     if (super_klass != NULL && super_klass->should_be_initialized()) {
1096       super_klass->initialize(THREAD);
1097     }
1098     // If C implements any interface that declares a non-static, concrete method,
1099     // the initialization of C triggers initialization of its super interfaces.
1100     // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1101     // having a superinterface that declares, non-static, concrete methods
1102     if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1103       initialize_super_interfaces(THREAD);
1104     }
1105 
1106     // If any exceptions, complete abruptly, throwing the same exception as above.
1107     if (HAS_PENDING_EXCEPTION) {
1108       Handle e(THREAD, PENDING_EXCEPTION);
1109       CLEAR_PENDING_EXCEPTION;
1110       {
1111         EXCEPTION_MARK;
1112         // Locks object, set state, and notify all waiting threads
1113         set_initialization_state_and_notify(initialization_error, THREAD);
1114         CLEAR_PENDING_EXCEPTION;
1115       }
1116       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1117       THROW_OOP(e());
1118     }
1119   }
1120 
1121   // Step 8
1122   // Initialize classes of flattenable fields
1123   {
1124     for (AllFieldStream fs(this); !fs.done(); fs.next()) {
1125       if (fs.is_flattenable()) {
1126         Klass* klass = this->get_value_field_klass_or_null(fs.index());
1127         if (klass == NULL) {
1128           assert(fs.access_flags().is_static() && fs.access_flags().is_flattenable(),
1129               "Otherwise should have been pre-loaded");
1130           klass = SystemDictionary::resolve_or_fail(field_signature(fs.index())->fundamental_name(THREAD),
1131               Handle(THREAD, class_loader()),
1132               Handle(THREAD, protection_domain()),
1133               true, CHECK);
1134           if (klass == NULL) {
1135             THROW(vmSymbols::java_lang_NoClassDefFoundError());
1136           }
1137           if (!klass->is_value()) {
1138             THROW(vmSymbols::java_lang_IncompatibleClassChangeError());
1139           }
1140           this->set_value_field_klass(fs.index(), klass);
1141         }
1142         InstanceKlass::cast(klass)->initialize(CHECK);
1143         if (fs.access_flags().is_static()) {
1144           if (java_mirror()->obj_field(fs.offset()) == NULL) {
1145             java_mirror()->obj_field_put(fs.offset(), ValueKlass::cast(klass)->default_value());
1146           }
1147         }
1148       }
1149     }
1150   }
1151 
1152 
1153   // Look for aot compiled methods for this klass, including class initializer.
1154   AOTLoader::load_for_klass(this, THREAD);
1155 
1156   // Step 9
1157   {
1158     DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1159     // Timer includes any side effects of class initialization (resolution,
1160     // etc), but not recursive entry into call_class_initializer().
1161     PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1162                              ClassLoader::perf_class_init_selftime(),
1163                              ClassLoader::perf_classes_inited(),
1164                              jt->get_thread_stat()->perf_recursion_counts_addr(),
1165                              jt->get_thread_stat()->perf_timers_addr(),
1166                              PerfClassTraceTime::CLASS_CLINIT);
1167     call_class_initializer(THREAD);
1168   }
1169 
1170   // Step 10
1171   if (!HAS_PENDING_EXCEPTION) {
1172     set_initialization_state_and_notify(fully_initialized, CHECK);
1173     {
1174       debug_only(vtable().verify(tty, true);)
1175     }
1176   }
1177   else {
1178     // Step 11 and 12
1179     Handle e(THREAD, PENDING_EXCEPTION);
1180     CLEAR_PENDING_EXCEPTION;
1181     // JVMTI has already reported the pending exception
1182     // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1183     JvmtiExport::clear_detected_exception(jt);
1184     {
1185       EXCEPTION_MARK;
1186       set_initialization_state_and_notify(initialization_error, THREAD);
1187       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
1188       // JVMTI has already reported the pending exception
1189       // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1190       JvmtiExport::clear_detected_exception(jt);
1191     }
1192     DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1193     if (e->is_a(SystemDictionary::Error_klass())) {
1194       THROW_OOP(e());
1195     } else {
1196       JavaCallArguments args(e);
1197       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
1198                 vmSymbols::throwable_void_signature(),
1199                 &args);
1200     }
1201   }
1202   DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1203 }
1204 
1205 
1206 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1207   Handle h_init_lock(THREAD, init_lock());
1208   if (h_init_lock() != NULL) {
1209     ObjectLocker ol(h_init_lock, THREAD);
1210     set_init_thread(NULL); // reset _init_thread before changing _init_state
1211     set_init_state(state);
1212     fence_and_clear_init_lock();
1213     ol.notify_all(CHECK);
1214   } else {
1215     assert(h_init_lock() != NULL, "The initialization state should never be set twice");
1216     set_init_thread(NULL); // reset _init_thread before changing _init_state
1217     set_init_state(state);
1218   }
1219 }
1220 
1221 Klass* InstanceKlass::implementor() const {
1222   Klass* volatile* k = adr_implementor();
1223   if (k == NULL) {
1224     return NULL;
1225   } else {
1226     // This load races with inserts, and therefore needs acquire.
1227     Klass* kls = OrderAccess::load_acquire(k);
1228     if (kls != NULL && !kls->is_loader_alive()) {
1229       return NULL;  // don't return unloaded class
1230     } else {
1231       return kls;
1232     }
1233   }
1234 }
1235 
1236 
1237 void InstanceKlass::set_implementor(Klass* k) {
1238   assert_lock_strong(Compile_lock);
1239   assert(is_interface(), "not interface");
1240   Klass* volatile* addr = adr_implementor();
1241   assert(addr != NULL, "null addr");
1242   if (addr != NULL) {
1243     OrderAccess::release_store(addr, k);
1244   }
1245 }
1246 
1247 int  InstanceKlass::nof_implementors() const {
1248   Klass* k = implementor();
1249   if (k == NULL) {
1250     return 0;
1251   } else if (k != this) {
1252     return 1;
1253   } else {
1254     return 2;
1255   }
1256 }
1257 
1258 // The embedded _implementor field can only record one implementor.
1259 // When there are more than one implementors, the _implementor field
1260 // is set to the interface Klass* itself. Following are the possible
1261 // values for the _implementor field:
1262 //   NULL                  - no implementor
1263 //   implementor Klass*    - one implementor
1264 //   self                  - more than one implementor
1265 //
1266 // The _implementor field only exists for interfaces.
1267 void InstanceKlass::add_implementor(Klass* k) {
1268   assert_lock_strong(Compile_lock);
1269   assert(is_interface(), "not interface");
1270   // Filter out my subinterfaces.
1271   // (Note: Interfaces are never on the subklass list.)
1272   if (InstanceKlass::cast(k)->is_interface()) return;
1273 
1274   // Filter out subclasses whose supers already implement me.
1275   // (Note: CHA must walk subclasses of direct implementors
1276   // in order to locate indirect implementors.)
1277   Klass* sk = k->super();
1278   if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
1279     // We only need to check one immediate superclass, since the
1280     // implements_interface query looks at transitive_interfaces.
1281     // Any supers of the super have the same (or fewer) transitive_interfaces.
1282     return;
1283 
1284   Klass* ik = implementor();
1285   if (ik == NULL) {
1286     set_implementor(k);
1287   } else if (ik != this) {
1288     // There is already an implementor. Use itself as an indicator of
1289     // more than one implementors.
1290     set_implementor(this);
1291   }
1292 
1293   // The implementor also implements the transitive_interfaces
1294   for (int index = 0; index < local_interfaces()->length(); index++) {
1295     InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
1296   }
1297 }
1298 
1299 void InstanceKlass::init_implementor() {
1300   if (is_interface()) {
1301     set_implementor(NULL);
1302   }
1303 }
1304 
1305 
1306 void InstanceKlass::process_interfaces(Thread *thread) {
1307   // link this class into the implementors list of every interface it implements
1308   for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
1309     assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
1310     InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
1311     assert(interf->is_interface(), "expected interface");
1312     interf->add_implementor(this);
1313   }
1314 }
1315 
1316 bool InstanceKlass::can_be_primary_super_slow() const {
1317   if (is_interface())
1318     return false;
1319   else
1320     return Klass::can_be_primary_super_slow();
1321 }
1322 
1323 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots,
1324                                                                Array<InstanceKlass*>* transitive_interfaces) {
1325   // The secondaries are the implemented interfaces.
1326   Array<InstanceKlass*>* interfaces = transitive_interfaces;
1327   int num_secondaries = num_extra_slots + interfaces->length();
1328   if (num_secondaries == 0) {
1329     // Must share this for correct bootstrapping!
1330     set_secondary_supers(Universe::the_empty_klass_array());
1331     return NULL;
1332   } else if (num_extra_slots == 0) {
1333     // The secondary super list is exactly the same as the transitive interfaces, so
1334     // let's use it instead of making a copy.
1335     // Redefine classes has to be careful not to delete this!
1336     // We need the cast because Array<Klass*> is NOT a supertype of Array<InstanceKlass*>,
1337     // (but it's safe to do here because we won't write into _secondary_supers from this point on).
1338     set_secondary_supers((Array<Klass*>*)(address)interfaces);
1339     return NULL;
1340   } else {
1341     // Copy transitive interfaces to a temporary growable array to be constructed
1342     // into the secondary super list with extra slots.
1343     GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
1344     for (int i = 0; i < interfaces->length(); i++) {
1345       secondaries->push(interfaces->at(i));
1346     }
1347     return secondaries;
1348   }
1349 }
1350 
1351 bool InstanceKlass::implements_interface(Klass* k) const {
1352   if (this == k) return true;
1353   assert(k->is_interface(), "should be an interface class");
1354   for (int i = 0; i < transitive_interfaces()->length(); i++) {
1355     if (transitive_interfaces()->at(i) == k) {
1356       return true;
1357     }
1358   }
1359   return false;
1360 }
1361 
1362 bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
1363   // Verify direct super interface
1364   if (this == k) return true;
1365   assert(k->is_interface(), "should be an interface class");
1366   for (int i = 0; i < local_interfaces()->length(); i++) {
1367     if (local_interfaces()->at(i) == k) {
1368       return true;
1369     }
1370   }
1371   return false;
1372 }
1373 
1374 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
1375   check_array_allocation_length(length, arrayOopDesc::max_array_length(T_OBJECT), CHECK_NULL);
1376   int size = objArrayOopDesc::object_size(length);
1377   Klass* ak = array_klass(n, CHECK_NULL);
1378   objArrayOop o = (objArrayOop)Universe::heap()->array_allocate(ak, size, length,
1379                                                                 /* do_zero */ true, CHECK_NULL);
1380   return o;
1381 }
1382 
1383 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
1384   if (TraceFinalizerRegistration) {
1385     tty->print("Registered ");
1386     i->print_value_on(tty);
1387     tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", p2i(i));
1388   }
1389   instanceHandle h_i(THREAD, i);
1390   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1391   JavaValue result(T_VOID);
1392   JavaCallArguments args(h_i);
1393   methodHandle mh (THREAD, Universe::finalizer_register_method());
1394   JavaCalls::call(&result, mh, &args, CHECK_NULL);
1395   return h_i();
1396 }
1397 
1398 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1399   bool has_finalizer_flag = has_finalizer(); // Query before possible GC
1400   int size = size_helper();  // Query before forming handle.
1401 
1402   instanceOop i;
1403 
1404   i = (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);
1405   if (has_finalizer_flag && !RegisterFinalizersAtInit) {
1406     i = register_finalizer(i, CHECK_NULL);
1407   }
1408   return i;
1409 }
1410 
1411 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1412   return instanceHandle(THREAD, allocate_instance(THREAD));
1413 }
1414 
1415 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1416   if (is_interface() || is_abstract()) {
1417     ResourceMark rm(THREAD);
1418     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1419               : vmSymbols::java_lang_InstantiationException(), external_name());
1420   }
1421   if (this == SystemDictionary::Class_klass()) {
1422     ResourceMark rm(THREAD);
1423     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1424               : vmSymbols::java_lang_IllegalAccessException(), external_name());
1425   }
1426 }
1427 
1428 Klass* InstanceKlass::array_klass_impl(ArrayStorageProperties storage_props, bool or_null, int n, TRAPS) {
1429   assert(storage_props.is_empty(), "Unexpected");
1430   // Need load-acquire for lock-free read
1431   if (array_klasses_acquire() == NULL) {
1432     if (or_null) return NULL;
1433 
1434     ResourceMark rm;
1435     {
1436       // Atomic creation of array_klasses
1437       MutexLocker ma(MultiArray_lock, THREAD);
1438 
1439       // Check if update has already taken place
1440       if (array_klasses() == NULL) {
1441         Klass*    k = ObjArrayKlass::allocate_objArray_klass(storage_props, 1, this, CHECK_NULL);
1442         // use 'release' to pair with lock-free load
1443         release_set_array_klasses(k);
1444       }
1445     }
1446   }
1447   // _this will always be set at this point
1448   ObjArrayKlass* oak = (ObjArrayKlass*)array_klasses();
1449   if (or_null) {
1450     return oak->array_klass_or_null(storage_props, n);
1451   }
1452   return oak->array_klass(storage_props, n, THREAD);
1453 }
1454 
1455 Klass* InstanceKlass::array_klass_impl(ArrayStorageProperties storage_props, bool or_null, TRAPS) {
1456   return array_klass_impl(storage_props, or_null, 1, THREAD);
1457 }
1458 
1459 static int call_class_initializer_counter = 0;   // for debugging
1460 
1461 Method* InstanceKlass::class_initializer() const {
1462   Method* clinit = find_method(
1463       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1464   if (clinit != NULL && clinit->is_class_initializer()) {
1465     return clinit;
1466   }
1467   return NULL;
1468 }
1469 
1470 void InstanceKlass::call_class_initializer(TRAPS) {
1471   if (ReplayCompiles &&
1472       (ReplaySuppressInitializers == 1 ||
1473        (ReplaySuppressInitializers >= 2 && class_loader() != NULL))) {
1474     // Hide the existence of the initializer for the purpose of replaying the compile
1475     return;
1476   }
1477 
1478   methodHandle h_method(THREAD, class_initializer());
1479   assert(!is_initialized(), "we cannot initialize twice");
1480   LogTarget(Info, class, init) lt;
1481   if (lt.is_enabled()) {
1482     ResourceMark rm;
1483     LogStream ls(lt);
1484     ls.print("%d Initializing ", call_class_initializer_counter++);
1485     name()->print_value_on(&ls);
1486     ls.print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", p2i(this));
1487   }
1488   if (h_method() != NULL) {
1489     JavaCallArguments args; // No arguments
1490     JavaValue result(T_VOID);
1491     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1492   }
1493 }
1494 
1495 
1496 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1497   InterpreterOopMap* entry_for) {
1498   // Lazily create the _oop_map_cache at first request
1499   // Lock-free access requires load_acquire.
1500   OopMapCache* oop_map_cache = OrderAccess::load_acquire(&_oop_map_cache);
1501   if (oop_map_cache == NULL) {
1502     MutexLocker x(OopMapCacheAlloc_lock,  Mutex::_no_safepoint_check_flag);
1503     // Check if _oop_map_cache was allocated while we were waiting for this lock
1504     if ((oop_map_cache = _oop_map_cache) == NULL) {
1505       oop_map_cache = new OopMapCache();
1506       // Ensure _oop_map_cache is stable, since it is examined without a lock
1507       OrderAccess::release_store(&_oop_map_cache, oop_map_cache);
1508     }
1509   }
1510   // _oop_map_cache is constant after init; lookup below does its own locking.
1511   oop_map_cache->lookup(method, bci, entry_for);
1512 }
1513 
1514 
1515 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1516   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1517     Symbol* f_name = fs.name();
1518     Symbol* f_sig  = fs.signature();
1519     if (f_name == name && f_sig == sig) {
1520       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1521       return true;
1522     }
1523   }
1524   return false;
1525 }
1526 
1527 
1528 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1529   const int n = local_interfaces()->length();
1530   for (int i = 0; i < n; i++) {
1531     Klass* intf1 = local_interfaces()->at(i);
1532     assert(intf1->is_interface(), "just checking type");
1533     // search for field in current interface
1534     if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
1535       assert(fd->is_static(), "interface field must be static");
1536       return intf1;
1537     }
1538     // search for field in direct superinterfaces
1539     Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
1540     if (intf2 != NULL) return intf2;
1541   }
1542   // otherwise field lookup fails
1543   return NULL;
1544 }
1545 
1546 
1547 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1548   // search order according to newest JVM spec (5.4.3.2, p.167).
1549   // 1) search for field in current klass
1550   if (find_local_field(name, sig, fd)) {
1551     return const_cast<InstanceKlass*>(this);
1552   }
1553   // 2) search for field recursively in direct superinterfaces
1554   { Klass* intf = find_interface_field(name, sig, fd);
1555     if (intf != NULL) return intf;
1556   }
1557   // 3) apply field lookup recursively if superclass exists
1558   { Klass* supr = super();
1559     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
1560   }
1561   // 4) otherwise field lookup fails
1562   return NULL;
1563 }
1564 
1565 
1566 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1567   // search order according to newest JVM spec (5.4.3.2, p.167).
1568   // 1) search for field in current klass
1569   if (find_local_field(name, sig, fd)) {
1570     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1571   }
1572   // 2) search for field recursively in direct superinterfaces
1573   if (is_static) {
1574     Klass* intf = find_interface_field(name, sig, fd);
1575     if (intf != NULL) return intf;
1576   }
1577   // 3) apply field lookup recursively if superclass exists
1578   { Klass* supr = super();
1579     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
1580   }
1581   // 4) otherwise field lookup fails
1582   return NULL;
1583 }
1584 
1585 
1586 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1587   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1588     if (fs.offset() == offset) {
1589       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1590       if (fd->is_static() == is_static) return true;
1591     }
1592   }
1593   return false;
1594 }
1595 
1596 
1597 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1598   Klass* klass = const_cast<InstanceKlass*>(this);
1599   while (klass != NULL) {
1600     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
1601       return true;
1602     }
1603     klass = klass->super();
1604   }
1605   return false;
1606 }
1607 
1608 
1609 void InstanceKlass::methods_do(void f(Method* method)) {
1610   // Methods aren't stable until they are loaded.  This can be read outside
1611   // a lock through the ClassLoaderData for profiling
1612   if (!is_loaded()) {
1613     return;
1614   }
1615 
1616   int len = methods()->length();
1617   for (int index = 0; index < len; index++) {
1618     Method* m = methods()->at(index);
1619     assert(m->is_method(), "must be method");
1620     f(m);
1621   }
1622 }
1623 
1624 
1625 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
1626   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1627     if (fs.access_flags().is_static()) {
1628       fieldDescriptor& fd = fs.field_descriptor();
1629       cl->do_field(&fd);
1630     }
1631   }
1632 }
1633 
1634 
1635 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
1636   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1637     if (fs.access_flags().is_static()) {
1638       fieldDescriptor& fd = fs.field_descriptor();
1639       f(&fd, mirror, CHECK);
1640     }
1641   }
1642 }
1643 
1644 
1645 static int compare_fields_by_offset(int* a, int* b) {
1646   return a[0] - b[0];
1647 }
1648 
1649 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
1650   InstanceKlass* super = superklass();
1651   if (super != NULL) {
1652     super->do_nonstatic_fields(cl);
1653   }
1654   fieldDescriptor fd;
1655   int length = java_fields_count();
1656   // In DebugInfo nonstatic fields are sorted by offset.
1657   int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
1658   int j = 0;
1659   for (int i = 0; i < length; i += 1) {
1660     fd.reinitialize(this, i);
1661     if (!fd.is_static()) {
1662       fields_sorted[j + 0] = fd.offset();
1663       fields_sorted[j + 1] = i;
1664       j += 2;
1665     }
1666   }
1667   if (j > 0) {
1668     length = j;
1669     // _sort_Fn is defined in growableArray.hpp.
1670     qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
1671     for (int i = 0; i < length; i += 2) {
1672       fd.reinitialize(this, fields_sorted[i + 1]);
1673       assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
1674       cl->do_field(&fd);
1675     }
1676   }
1677   FREE_C_HEAP_ARRAY(int, fields_sorted);
1678 }
1679 
1680 
1681 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
1682   if (array_klasses() != NULL)
1683     ArrayKlass::cast(array_klasses())->array_klasses_do(f);
1684 }
1685 
1686 #ifdef ASSERT
1687 static int linear_search(const Array<Method*>* methods,
1688                          const Symbol* name,
1689                          const Symbol* signature) {
1690   const int len = methods->length();
1691   for (int index = 0; index < len; index++) {
1692     const Method* const m = methods->at(index);
1693     assert(m->is_method(), "must be method");
1694     if (m->signature() == signature && m->name() == name) {
1695        return index;
1696     }
1697   }
1698   return -1;
1699 }
1700 #endif
1701 
1702 static int binary_search(const Array<Method*>* methods, const Symbol* name) {
1703   int len = methods->length();
1704   // methods are sorted, so do binary search
1705   int l = 0;
1706   int h = len - 1;
1707   while (l <= h) {
1708     int mid = (l + h) >> 1;
1709     Method* m = methods->at(mid);
1710     assert(m->is_method(), "must be method");
1711     int res = m->name()->fast_compare(name);
1712     if (res == 0) {
1713       return mid;
1714     } else if (res < 0) {
1715       l = mid + 1;
1716     } else {
1717       h = mid - 1;
1718     }
1719   }
1720   return -1;
1721 }
1722 
1723 // find_method looks up the name/signature in the local methods array
1724 Method* InstanceKlass::find_method(const Symbol* name,
1725                                    const Symbol* signature) const {
1726   return find_method_impl(name, signature, find_overpass, find_static, find_private);
1727 }
1728 
1729 Method* InstanceKlass::find_method_impl(const Symbol* name,
1730                                         const Symbol* signature,
1731                                         OverpassLookupMode overpass_mode,
1732                                         StaticLookupMode static_mode,
1733                                         PrivateLookupMode private_mode) const {
1734   return InstanceKlass::find_method_impl(methods(),
1735                                          name,
1736                                          signature,
1737                                          overpass_mode,
1738                                          static_mode,
1739                                          private_mode);
1740 }
1741 
1742 // find_instance_method looks up the name/signature in the local methods array
1743 // and skips over static methods
1744 Method* InstanceKlass::find_instance_method(const Array<Method*>* methods,
1745                                             const Symbol* name,
1746                                             const Symbol* signature,
1747                                             PrivateLookupMode private_mode) {
1748   Method* const meth = InstanceKlass::find_method_impl(methods,
1749                                                  name,
1750                                                  signature,
1751                                                  find_overpass,
1752                                                  skip_static,
1753                                                  private_mode);
1754   assert(((meth == NULL) || !meth->is_static()),
1755     "find_instance_method should have skipped statics");
1756   return meth;
1757 }
1758 
1759 // find_instance_method looks up the name/signature in the local methods array
1760 // and skips over static methods
1761 Method* InstanceKlass::find_instance_method(const Symbol* name,
1762                                             const Symbol* signature,
1763                                             PrivateLookupMode private_mode) const {
1764   return InstanceKlass::find_instance_method(methods(), name, signature, private_mode);
1765 }
1766 
1767 // Find looks up the name/signature in the local methods array
1768 // and filters on the overpass, static and private flags
1769 // This returns the first one found
1770 // note that the local methods array can have up to one overpass, one static
1771 // and one instance (private or not) with the same name/signature
1772 Method* InstanceKlass::find_local_method(const Symbol* name,
1773                                          const Symbol* signature,
1774                                          OverpassLookupMode overpass_mode,
1775                                          StaticLookupMode static_mode,
1776                                          PrivateLookupMode private_mode) const {
1777   return InstanceKlass::find_method_impl(methods(),
1778                                          name,
1779                                          signature,
1780                                          overpass_mode,
1781                                          static_mode,
1782                                          private_mode);
1783 }
1784 
1785 // Find looks up the name/signature in the local methods array
1786 // and filters on the overpass, static and private flags
1787 // This returns the first one found
1788 // note that the local methods array can have up to one overpass, one static
1789 // and one instance (private or not) with the same name/signature
1790 Method* InstanceKlass::find_local_method(const Array<Method*>* methods,
1791                                          const Symbol* name,
1792                                          const Symbol* signature,
1793                                          OverpassLookupMode overpass_mode,
1794                                          StaticLookupMode static_mode,
1795                                          PrivateLookupMode private_mode) {
1796   return InstanceKlass::find_method_impl(methods,
1797                                          name,
1798                                          signature,
1799                                          overpass_mode,
1800                                          static_mode,
1801                                          private_mode);
1802 }
1803 
1804 Method* InstanceKlass::find_method(const Array<Method*>* methods,
1805                                    const Symbol* name,
1806                                    const Symbol* signature) {
1807   return InstanceKlass::find_method_impl(methods,
1808                                          name,
1809                                          signature,
1810                                          find_overpass,
1811                                          find_static,
1812                                          find_private);
1813 }
1814 
1815 Method* InstanceKlass::find_method_impl(const Array<Method*>* methods,
1816                                         const Symbol* name,
1817                                         const Symbol* signature,
1818                                         OverpassLookupMode overpass_mode,
1819                                         StaticLookupMode static_mode,
1820                                         PrivateLookupMode private_mode) {
1821   int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode);
1822   return hit >= 0 ? methods->at(hit): NULL;
1823 }
1824 
1825 // true if method matches signature and conforms to skipping_X conditions.
1826 static bool method_matches(const Method* m,
1827                            const Symbol* signature,
1828                            bool skipping_overpass,
1829                            bool skipping_static,
1830                            bool skipping_private) {
1831   return ((m->signature() == signature) &&
1832     (!skipping_overpass || !m->is_overpass()) &&
1833     (!skipping_static || !m->is_static()) &&
1834     (!skipping_private || !m->is_private()));
1835 }
1836 
1837 // Used directly for default_methods to find the index into the
1838 // default_vtable_indices, and indirectly by find_method
1839 // find_method_index looks in the local methods array to return the index
1840 // of the matching name/signature. If, overpass methods are being ignored,
1841 // the search continues to find a potential non-overpass match.  This capability
1842 // is important during method resolution to prefer a static method, for example,
1843 // over an overpass method.
1844 // There is the possibility in any _method's array to have the same name/signature
1845 // for a static method, an overpass method and a local instance method
1846 // To correctly catch a given method, the search criteria may need
1847 // to explicitly skip the other two. For local instance methods, it
1848 // is often necessary to skip private methods
1849 int InstanceKlass::find_method_index(const Array<Method*>* methods,
1850                                      const Symbol* name,
1851                                      const Symbol* signature,
1852                                      OverpassLookupMode overpass_mode,
1853                                      StaticLookupMode static_mode,
1854                                      PrivateLookupMode private_mode) {
1855   const bool skipping_overpass = (overpass_mode == skip_overpass);
1856   const bool skipping_static = (static_mode == skip_static);
1857   const bool skipping_private = (private_mode == skip_private);
1858   const int hit = binary_search(methods, name);
1859   if (hit != -1) {
1860     const Method* const m = methods->at(hit);
1861 
1862     // Do linear search to find matching signature.  First, quick check
1863     // for common case, ignoring overpasses if requested.
1864     if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1865       return hit;
1866     }
1867 
1868     // search downwards through overloaded methods
1869     int i;
1870     for (i = hit - 1; i >= 0; --i) {
1871         const Method* const m = methods->at(i);
1872         assert(m->is_method(), "must be method");
1873         if (m->name() != name) {
1874           break;
1875         }
1876         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1877           return i;
1878         }
1879     }
1880     // search upwards
1881     for (i = hit + 1; i < methods->length(); ++i) {
1882         const Method* const m = methods->at(i);
1883         assert(m->is_method(), "must be method");
1884         if (m->name() != name) {
1885           break;
1886         }
1887         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1888           return i;
1889         }
1890     }
1891     // not found
1892 #ifdef ASSERT
1893     const int index = (skipping_overpass || skipping_static || skipping_private) ? -1 :
1894       linear_search(methods, name, signature);
1895     assert(-1 == index, "binary search should have found entry %d", index);
1896 #endif
1897   }
1898   return -1;
1899 }
1900 
1901 int InstanceKlass::find_method_by_name(const Symbol* name, int* end) const {
1902   return find_method_by_name(methods(), name, end);
1903 }
1904 
1905 int InstanceKlass::find_method_by_name(const Array<Method*>* methods,
1906                                        const Symbol* name,
1907                                        int* end_ptr) {
1908   assert(end_ptr != NULL, "just checking");
1909   int start = binary_search(methods, name);
1910   int end = start + 1;
1911   if (start != -1) {
1912     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
1913     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
1914     *end_ptr = end;
1915     return start;
1916   }
1917   return -1;
1918 }
1919 
1920 // uncached_lookup_method searches both the local class methods array and all
1921 // superclasses methods arrays, skipping any overpass methods in superclasses,
1922 // and possibly skipping private methods.
1923 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
1924                                               const Symbol* signature,
1925                                               OverpassLookupMode overpass_mode,
1926                                               PrivateLookupMode private_mode) const {
1927   OverpassLookupMode overpass_local_mode = overpass_mode;
1928   const Klass* klass = this;
1929   while (klass != NULL) {
1930     Method* const method = InstanceKlass::cast(klass)->find_method_impl(name,
1931                                                                         signature,
1932                                                                         overpass_local_mode,
1933                                                                         find_static,
1934                                                                         private_mode);
1935     if (method != NULL) {
1936       return method;
1937     }
1938     if (name == vmSymbols::object_initializer_name()) {
1939       break;  // <init> is never inherited, not even as a static factory
1940     }
1941     klass = klass->super();
1942     overpass_local_mode = skip_overpass;   // Always ignore overpass methods in superclasses
1943   }
1944   return NULL;
1945 }
1946 
1947 #ifdef ASSERT
1948 // search through class hierarchy and return true if this class or
1949 // one of the superclasses was redefined
1950 bool InstanceKlass::has_redefined_this_or_super() const {
1951   const Klass* klass = this;
1952   while (klass != NULL) {
1953     if (InstanceKlass::cast(klass)->has_been_redefined()) {
1954       return true;
1955     }
1956     klass = klass->super();
1957   }
1958   return false;
1959 }
1960 #endif
1961 
1962 // lookup a method in the default methods list then in all transitive interfaces
1963 // Do NOT return private or static methods
1964 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
1965                                                          Symbol* signature) const {
1966   Method* m = NULL;
1967   if (default_methods() != NULL) {
1968     m = find_method(default_methods(), name, signature);
1969   }
1970   // Look up interfaces
1971   if (m == NULL) {
1972     m = lookup_method_in_all_interfaces(name, signature, find_defaults);
1973   }
1974   return m;
1975 }
1976 
1977 // lookup a method in all the interfaces that this class implements
1978 // Do NOT return private or static methods, new in JDK8 which are not externally visible
1979 // They should only be found in the initial InterfaceMethodRef
1980 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
1981                                                        Symbol* signature,
1982                                                        DefaultsLookupMode defaults_mode) const {
1983   Array<InstanceKlass*>* all_ifs = transitive_interfaces();
1984   int num_ifs = all_ifs->length();
1985   InstanceKlass *ik = NULL;
1986   for (int i = 0; i < num_ifs; i++) {
1987     ik = all_ifs->at(i);
1988     Method* m = ik->lookup_method(name, signature);
1989     if (m != NULL && m->is_public() && !m->is_static() &&
1990         ((defaults_mode != skip_defaults) || !m->is_default_method())) {
1991       return m;
1992     }
1993   }
1994   return NULL;
1995 }
1996 
1997 /* jni_id_for_impl for jfieldIds only */
1998 JNIid* InstanceKlass::jni_id_for_impl(int offset) {
1999   MutexLocker ml(JfieldIdCreation_lock);
2000   // Retry lookup after we got the lock
2001   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
2002   if (probe == NULL) {
2003     // Slow case, allocate new static field identifier
2004     probe = new JNIid(this, offset, jni_ids());
2005     set_jni_ids(probe);
2006   }
2007   return probe;
2008 }
2009 
2010 
2011 /* jni_id_for for jfieldIds only */
2012 JNIid* InstanceKlass::jni_id_for(int offset) {
2013   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
2014   if (probe == NULL) {
2015     probe = jni_id_for_impl(offset);
2016   }
2017   return probe;
2018 }
2019 
2020 u2 InstanceKlass::enclosing_method_data(int offset) const {
2021   const Array<jushort>* const inner_class_list = inner_classes();
2022   if (inner_class_list == NULL) {
2023     return 0;
2024   }
2025   const int length = inner_class_list->length();
2026   if (length % inner_class_next_offset == 0) {
2027     return 0;
2028   }
2029   const int index = length - enclosing_method_attribute_size;
2030   assert(offset < enclosing_method_attribute_size, "invalid offset");
2031   return inner_class_list->at(index + offset);
2032 }
2033 
2034 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
2035                                                  u2 method_index) {
2036   Array<jushort>* inner_class_list = inner_classes();
2037   assert (inner_class_list != NULL, "_inner_classes list is not set up");
2038   int length = inner_class_list->length();
2039   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
2040     int index = length - enclosing_method_attribute_size;
2041     inner_class_list->at_put(
2042       index + enclosing_method_class_index_offset, class_index);
2043     inner_class_list->at_put(
2044       index + enclosing_method_method_index_offset, method_index);
2045   }
2046 }
2047 
2048 // Lookup or create a jmethodID.
2049 // This code is called by the VMThread and JavaThreads so the
2050 // locking has to be done very carefully to avoid deadlocks
2051 // and/or other cache consistency problems.
2052 //
2053 jmethodID InstanceKlass::get_jmethod_id(const methodHandle& method_h) {
2054   size_t idnum = (size_t)method_h->method_idnum();
2055   jmethodID* jmeths = methods_jmethod_ids_acquire();
2056   size_t length = 0;
2057   jmethodID id = NULL;
2058 
2059   // We use a double-check locking idiom here because this cache is
2060   // performance sensitive. In the normal system, this cache only
2061   // transitions from NULL to non-NULL which is safe because we use
2062   // release_set_methods_jmethod_ids() to advertise the new cache.
2063   // A partially constructed cache should never be seen by a racing
2064   // thread. We also use release_store() to save a new jmethodID
2065   // in the cache so a partially constructed jmethodID should never be
2066   // seen either. Cache reads of existing jmethodIDs proceed without a
2067   // lock, but cache writes of a new jmethodID requires uniqueness and
2068   // creation of the cache itself requires no leaks so a lock is
2069   // generally acquired in those two cases.
2070   //
2071   // If the RedefineClasses() API has been used, then this cache can
2072   // grow and we'll have transitions from non-NULL to bigger non-NULL.
2073   // Cache creation requires no leaks and we require safety between all
2074   // cache accesses and freeing of the old cache so a lock is generally
2075   // acquired when the RedefineClasses() API has been used.
2076 
2077   if (jmeths != NULL) {
2078     // the cache already exists
2079     if (!idnum_can_increment()) {
2080       // the cache can't grow so we can just get the current values
2081       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
2082     } else {
2083       // cache can grow so we have to be more careful
2084       if (Threads::number_of_threads() == 0 ||
2085           SafepointSynchronize::is_at_safepoint()) {
2086         // we're single threaded or at a safepoint - no locking needed
2087         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
2088       } else {
2089         MutexLocker ml(JmethodIdCreation_lock);
2090         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
2091       }
2092     }
2093   }
2094   // implied else:
2095   // we need to allocate a cache so default length and id values are good
2096 
2097   if (jmeths == NULL ||   // no cache yet
2098       length <= idnum ||  // cache is too short
2099       id == NULL) {       // cache doesn't contain entry
2100 
2101     // This function can be called by the VMThread so we have to do all
2102     // things that might block on a safepoint before grabbing the lock.
2103     // Otherwise, we can deadlock with the VMThread or have a cache
2104     // consistency issue. These vars keep track of what we might have
2105     // to free after the lock is dropped.
2106     jmethodID  to_dealloc_id     = NULL;
2107     jmethodID* to_dealloc_jmeths = NULL;
2108 
2109     // may not allocate new_jmeths or use it if we allocate it
2110     jmethodID* new_jmeths = NULL;
2111     if (length <= idnum) {
2112       // allocate a new cache that might be used
2113       size_t size = MAX2(idnum+1, (size_t)idnum_allocated_count());
2114       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
2115       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
2116       // cache size is stored in element[0], other elements offset by one
2117       new_jmeths[0] = (jmethodID)size;
2118     }
2119 
2120     // allocate a new jmethodID that might be used
2121     jmethodID new_id = NULL;
2122     if (method_h->is_old() && !method_h->is_obsolete()) {
2123       // The method passed in is old (but not obsolete), we need to use the current version
2124       Method* current_method = method_with_idnum((int)idnum);
2125       assert(current_method != NULL, "old and but not obsolete, so should exist");
2126       new_id = Method::make_jmethod_id(class_loader_data(), current_method);
2127     } else {
2128       // It is the current version of the method or an obsolete method,
2129       // use the version passed in
2130       new_id = Method::make_jmethod_id(class_loader_data(), method_h());
2131     }
2132 
2133     if (Threads::number_of_threads() == 0 ||
2134         SafepointSynchronize::is_at_safepoint()) {
2135       // we're single threaded or at a safepoint - no locking needed
2136       id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,
2137                                           &to_dealloc_id, &to_dealloc_jmeths);
2138     } else {
2139       MutexLocker ml(JmethodIdCreation_lock);
2140       id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,
2141                                           &to_dealloc_id, &to_dealloc_jmeths);
2142     }
2143 
2144     // The lock has been dropped so we can free resources.
2145     // Free up either the old cache or the new cache if we allocated one.
2146     if (to_dealloc_jmeths != NULL) {
2147       FreeHeap(to_dealloc_jmeths);
2148     }
2149     // free up the new ID since it wasn't needed
2150     if (to_dealloc_id != NULL) {
2151       Method::destroy_jmethod_id(class_loader_data(), to_dealloc_id);
2152     }
2153   }
2154   return id;
2155 }
2156 
2157 // Figure out how many jmethodIDs haven't been allocated, and make
2158 // sure space for them is pre-allocated.  This makes getting all
2159 // method ids much, much faster with classes with more than 8
2160 // methods, and has a *substantial* effect on performance with jvmti
2161 // code that loads all jmethodIDs for all classes.
2162 void InstanceKlass::ensure_space_for_methodids(int start_offset) {
2163   int new_jmeths = 0;
2164   int length = methods()->length();
2165   for (int index = start_offset; index < length; index++) {
2166     Method* m = methods()->at(index);
2167     jmethodID id = m->find_jmethod_id_or_null();
2168     if (id == NULL) {
2169       new_jmeths++;
2170     }
2171   }
2172   if (new_jmeths != 0) {
2173     Method::ensure_jmethod_ids(class_loader_data(), new_jmeths);
2174   }
2175 }
2176 
2177 // Common code to fetch the jmethodID from the cache or update the
2178 // cache with the new jmethodID. This function should never do anything
2179 // that causes the caller to go to a safepoint or we can deadlock with
2180 // the VMThread or have cache consistency issues.
2181 //
2182 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
2183             size_t idnum, jmethodID new_id,
2184             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
2185             jmethodID** to_dealloc_jmeths_p) {
2186   assert(new_id != NULL, "sanity check");
2187   assert(to_dealloc_id_p != NULL, "sanity check");
2188   assert(to_dealloc_jmeths_p != NULL, "sanity check");
2189   assert(Threads::number_of_threads() == 0 ||
2190          SafepointSynchronize::is_at_safepoint() ||
2191          JmethodIdCreation_lock->owned_by_self(), "sanity check");
2192 
2193   // reacquire the cache - we are locked, single threaded or at a safepoint
2194   jmethodID* jmeths = methods_jmethod_ids_acquire();
2195   jmethodID  id     = NULL;
2196   size_t     length = 0;
2197 
2198   if (jmeths == NULL ||                         // no cache yet
2199       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
2200     if (jmeths != NULL) {
2201       // copy any existing entries from the old cache
2202       for (size_t index = 0; index < length; index++) {
2203         new_jmeths[index+1] = jmeths[index+1];
2204       }
2205       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
2206     }
2207     release_set_methods_jmethod_ids(jmeths = new_jmeths);
2208   } else {
2209     // fetch jmethodID (if any) from the existing cache
2210     id = jmeths[idnum+1];
2211     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
2212   }
2213   if (id == NULL) {
2214     // No matching jmethodID in the existing cache or we have a new
2215     // cache or we just grew the cache. This cache write is done here
2216     // by the first thread to win the foot race because a jmethodID
2217     // needs to be unique once it is generally available.
2218     id = new_id;
2219 
2220     // The jmethodID cache can be read while unlocked so we have to
2221     // make sure the new jmethodID is complete before installing it
2222     // in the cache.
2223     OrderAccess::release_store(&jmeths[idnum+1], id);
2224   } else {
2225     *to_dealloc_id_p = new_id; // save new id for later delete
2226   }
2227   return id;
2228 }
2229 
2230 
2231 // Common code to get the jmethodID cache length and the jmethodID
2232 // value at index idnum if there is one.
2233 //
2234 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
2235        size_t idnum, size_t *length_p, jmethodID* id_p) {
2236   assert(cache != NULL, "sanity check");
2237   assert(length_p != NULL, "sanity check");
2238   assert(id_p != NULL, "sanity check");
2239 
2240   // cache size is stored in element[0], other elements offset by one
2241   *length_p = (size_t)cache[0];
2242   if (*length_p <= idnum) {  // cache is too short
2243     *id_p = NULL;
2244   } else {
2245     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
2246   }
2247 }
2248 
2249 
2250 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
2251 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
2252   size_t idnum = (size_t)method->method_idnum();
2253   jmethodID* jmeths = methods_jmethod_ids_acquire();
2254   size_t length;                                // length assigned as debugging crumb
2255   jmethodID id = NULL;
2256   if (jmeths != NULL &&                         // If there is a cache
2257       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
2258     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
2259   }
2260   return id;
2261 }
2262 
2263 inline DependencyContext InstanceKlass::dependencies() {
2264   DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);
2265   return dep_context;
2266 }
2267 
2268 int InstanceKlass::mark_dependent_nmethods(KlassDepChange& changes) {
2269   return dependencies().mark_dependent_nmethods(changes);
2270 }
2271 
2272 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2273   dependencies().add_dependent_nmethod(nm);
2274 }
2275 
2276 void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
2277   dependencies().remove_dependent_nmethod(nm);
2278 }
2279 
2280 void InstanceKlass::clean_dependency_context() {
2281   dependencies().clean_unloading_dependents();
2282 }
2283 
2284 #ifndef PRODUCT
2285 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2286   dependencies().print_dependent_nmethods(verbose);
2287 }
2288 
2289 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2290   return dependencies().is_dependent_nmethod(nm);
2291 }
2292 #endif //PRODUCT
2293 
2294 void InstanceKlass::clean_weak_instanceklass_links() {
2295   clean_implementors_list();
2296   clean_method_data();
2297 }
2298 
2299 void InstanceKlass::clean_implementors_list() {
2300   assert(is_loader_alive(), "this klass should be live");
2301   if (is_interface()) {
2302     assert (ClassUnloading, "only called for ClassUnloading");
2303     for (;;) {
2304       // Use load_acquire due to competing with inserts
2305       Klass* impl = OrderAccess::load_acquire(adr_implementor());
2306       if (impl != NULL && !impl->is_loader_alive()) {
2307         // NULL this field, might be an unloaded klass or NULL
2308         Klass* volatile* klass = adr_implementor();
2309         if (Atomic::cmpxchg((Klass*)NULL, klass, impl) == impl) {
2310           // Successfully unlinking implementor.
2311           if (log_is_enabled(Trace, class, unload)) {
2312             ResourceMark rm;
2313             log_trace(class, unload)("unlinking class (implementor): %s", impl->external_name());
2314           }
2315           return;
2316         }
2317       } else {
2318         return;
2319       }
2320     }
2321   }
2322 }
2323 
2324 void InstanceKlass::clean_method_data() {
2325   for (int m = 0; m < methods()->length(); m++) {
2326     MethodData* mdo = methods()->at(m)->method_data();
2327     if (mdo != NULL) {
2328       MutexLocker ml(SafepointSynchronize::is_at_safepoint() ? NULL : mdo->extra_data_lock());
2329       mdo->clean_method_data(/*always_clean*/false);
2330     }
2331   }
2332 }
2333 
2334 bool InstanceKlass::supers_have_passed_fingerprint_checks() {
2335   if (java_super() != NULL && !java_super()->has_passed_fingerprint_check()) {
2336     ResourceMark rm;
2337     log_trace(class, fingerprint)("%s : super %s not fingerprinted", external_name(), java_super()->external_name());
2338     return false;
2339   }
2340 
2341   Array<InstanceKlass*>* local_interfaces = this->local_interfaces();
2342   if (local_interfaces != NULL) {
2343     int length = local_interfaces->length();
2344     for (int i = 0; i < length; i++) {
2345       InstanceKlass* intf = local_interfaces->at(i);
2346       if (!intf->has_passed_fingerprint_check()) {
2347         ResourceMark rm;
2348         log_trace(class, fingerprint)("%s : interface %s not fingerprinted", external_name(), intf->external_name());
2349         return false;
2350       }
2351     }
2352   }
2353 
2354   return true;
2355 }
2356 
2357 bool InstanceKlass::should_store_fingerprint(bool is_unsafe_anonymous) {
2358 #if INCLUDE_AOT
2359   // We store the fingerprint into the InstanceKlass only in the following 2 cases:
2360   if (CalculateClassFingerprint) {
2361     // (1) We are running AOT to generate a shared library.
2362     return true;
2363   }
2364   if (DumpSharedSpaces || DynamicDumpSharedSpaces) {
2365     // (2) We are running -Xshare:dump or -XX:ArchiveClassesAtExit to create a shared archive
2366     return true;
2367   }
2368   if (UseAOT && is_unsafe_anonymous) {
2369     // (3) We are using AOT code from a shared library and see an unsafe anonymous class
2370     return true;
2371   }
2372 #endif
2373 
2374   // In all other cases we might set the _misc_has_passed_fingerprint_check bit,
2375   // but do not store the 64-bit fingerprint to save space.
2376   return false;
2377 }
2378 
2379 bool InstanceKlass::has_stored_fingerprint() const {
2380 #if INCLUDE_AOT
2381   return should_store_fingerprint() || is_shared();
2382 #else
2383   return false;
2384 #endif
2385 }
2386 
2387 uint64_t InstanceKlass::get_stored_fingerprint() const {
2388   address adr = adr_fingerprint();
2389   if (adr != NULL) {
2390     return (uint64_t)Bytes::get_native_u8(adr); // adr may not be 64-bit aligned
2391   }
2392   return 0;
2393 }
2394 
2395 void InstanceKlass::store_fingerprint(uint64_t fingerprint) {
2396   address adr = adr_fingerprint();
2397   if (adr != NULL) {
2398     Bytes::put_native_u8(adr, (u8)fingerprint); // adr may not be 64-bit aligned
2399 
2400     ResourceMark rm;
2401     log_trace(class, fingerprint)("stored as " PTR64_FORMAT " for class %s", fingerprint, external_name());
2402   }
2403 }
2404 
2405 void InstanceKlass::metaspace_pointers_do(MetaspaceClosure* it) {
2406   Klass::metaspace_pointers_do(it);
2407 
2408   if (log_is_enabled(Trace, cds)) {
2409     ResourceMark rm;
2410     log_trace(cds)("Iter(InstanceKlass): %p (%s)", this, external_name());
2411   }
2412 
2413   it->push(&_annotations);
2414   it->push((Klass**)&_array_klasses);
2415   it->push(&_constants);
2416   it->push(&_inner_classes);
2417   it->push(&_array_name);
2418 #if INCLUDE_JVMTI
2419   it->push(&_previous_versions);
2420 #endif
2421   it->push(&_methods);
2422   it->push(&_default_methods);
2423   it->push(&_local_interfaces);
2424   it->push(&_transitive_interfaces);
2425   it->push(&_method_ordering);
2426   it->push(&_default_vtable_indices);
2427   it->push(&_fields);
2428 
2429   if (itable_length() > 0) {
2430     itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2431     int method_table_offset_in_words = ioe->offset()/wordSize;
2432     int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2433                          / itableOffsetEntry::size();
2434 
2435     for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2436       if (ioe->interface_klass() != NULL) {
2437         it->push(ioe->interface_klass_addr());
2438         itableMethodEntry* ime = ioe->first_method_entry(this);
2439         int n = klassItable::method_count_for_interface(ioe->interface_klass());
2440         for (int index = 0; index < n; index ++) {
2441           it->push(ime[index].method_addr());
2442         }
2443       }
2444     }
2445   }
2446 
2447   it->push(&_nest_members);
2448 }
2449 
2450 void InstanceKlass::remove_unshareable_info() {
2451   Klass::remove_unshareable_info();
2452 
2453   if (is_in_error_state()) {
2454     // Classes are attempted to link during dumping and may fail,
2455     // but these classes are still in the dictionary and class list in CLD.
2456     // Check in_error state first because in_error is > linked state, so
2457     // is_linked() is true.
2458     // If there's a linking error, there is nothing else to remove.
2459     return;
2460   }
2461 
2462   // Reset to the 'allocated' state to prevent any premature accessing to
2463   // a shared class at runtime while the class is still being loaded and
2464   // restored. A class' init_state is set to 'loaded' at runtime when it's
2465   // being added to class hierarchy (see SystemDictionary:::add_to_hierarchy()).
2466   _init_state = allocated;
2467 
2468   {
2469     MutexLocker ml(Compile_lock);
2470     init_implementor();
2471   }
2472 
2473   constants()->remove_unshareable_info();
2474 
2475   for (int i = 0; i < methods()->length(); i++) {
2476     Method* m = methods()->at(i);
2477     m->remove_unshareable_info();
2478   }
2479 
2480   // do array classes also.
2481   if (array_klasses() != NULL) {
2482     array_klasses()->remove_unshareable_info();
2483   }
2484 
2485   // These are not allocated from metaspace. They are safe to set to NULL.
2486   _source_debug_extension = NULL;
2487   _dep_context = NULL;
2488   _osr_nmethods_head = NULL;
2489 #if INCLUDE_JVMTI
2490   _breakpoints = NULL;
2491   _previous_versions = NULL;
2492   _cached_class_file = NULL;
2493 #endif
2494 
2495   _init_thread = NULL;
2496   _methods_jmethod_ids = NULL;
2497   _jni_ids = NULL;
2498   _oop_map_cache = NULL;
2499   // clear _nest_host to ensure re-load at runtime
2500   _nest_host = NULL;
2501 }
2502 
2503 void InstanceKlass::remove_java_mirror() {
2504   Klass::remove_java_mirror();
2505 
2506   // do array classes also.
2507   if (array_klasses() != NULL) {
2508     array_klasses()->remove_java_mirror();
2509   }
2510 }
2511 
2512 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
2513   // SystemDictionary::add_to_hierarchy() sets the init_state to loaded
2514   // before the InstanceKlass is added to the SystemDictionary. Make
2515   // sure the current state is <loaded.
2516   assert(!is_loaded(), "invalid init state");
2517   set_package(loader_data, CHECK);
2518   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2519 
2520   Array<Method*>* methods = this->methods();
2521   int num_methods = methods->length();
2522   for (int index = 0; index < num_methods; ++index) {
2523     methods->at(index)->restore_unshareable_info(CHECK);
2524   }
2525   if (JvmtiExport::has_redefined_a_class()) {
2526     // Reinitialize vtable because RedefineClasses may have changed some
2527     // entries in this vtable for super classes so the CDS vtable might
2528     // point to old or obsolete entries.  RedefineClasses doesn't fix up
2529     // vtables in the shared system dictionary, only the main one.
2530     // It also redefines the itable too so fix that too.
2531     vtable().initialize_vtable(false, CHECK);
2532     itable().initialize_itable(false, CHECK);
2533   }
2534 
2535   // restore constant pool resolved references
2536   constants()->restore_unshareable_info(CHECK);
2537 
2538   if (array_klasses() != NULL) {
2539     // Array classes have null protection domain.
2540     // --> see ArrayKlass::complete_create_array_klass()
2541     array_klasses()->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);
2542   }
2543 }
2544 
2545 // returns true IFF is_in_error_state() has been changed as a result of this call.
2546 bool InstanceKlass::check_sharing_error_state() {
2547   assert(DumpSharedSpaces, "should only be called during dumping");
2548   bool old_state = is_in_error_state();
2549 
2550   if (!is_in_error_state()) {
2551     bool bad = false;
2552     for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) {
2553       if (sup->is_in_error_state()) {
2554         bad = true;
2555         break;
2556       }
2557     }
2558     if (!bad) {
2559       Array<InstanceKlass*>* interfaces = transitive_interfaces();
2560       for (int i = 0; i < interfaces->length(); i++) {
2561         InstanceKlass* iface = interfaces->at(i);
2562         if (iface->is_in_error_state()) {
2563           bad = true;
2564           break;
2565         }
2566       }
2567     }
2568 
2569     if (bad) {
2570       set_in_error_state();
2571     }
2572   }
2573 
2574   return (old_state != is_in_error_state());
2575 }
2576 
2577 void InstanceKlass::set_class_loader_type(s2 loader_type) {
2578   switch (loader_type) {
2579   case ClassLoader::BOOT_LOADER:
2580     _misc_flags |= _misc_is_shared_boot_class;
2581     break;
2582   case ClassLoader::PLATFORM_LOADER:
2583     _misc_flags |= _misc_is_shared_platform_class;
2584     break;
2585   case ClassLoader::APP_LOADER:
2586     _misc_flags |= _misc_is_shared_app_class;
2587     break;
2588   default:
2589     ShouldNotReachHere();
2590     break;
2591   }
2592 }
2593 
2594 #if INCLUDE_JVMTI
2595 static void clear_all_breakpoints(Method* m) {
2596   m->clear_all_breakpoints();
2597 }
2598 #endif
2599 
2600 void InstanceKlass::unload_class(InstanceKlass* ik) {
2601   // Release dependencies.
2602   ik->dependencies().remove_all_dependents();
2603 
2604   // notify the debugger
2605   if (JvmtiExport::should_post_class_unload()) {
2606     JvmtiExport::post_class_unload(ik);
2607   }
2608 
2609   // notify ClassLoadingService of class unload
2610   ClassLoadingService::notify_class_unloaded(ik);
2611 
2612   if (DumpSharedSpaces || DynamicDumpSharedSpaces) {
2613     SystemDictionaryShared::remove_dumptime_info(ik);
2614   }
2615 
2616   if (log_is_enabled(Info, class, unload)) {
2617     ResourceMark rm;
2618     log_info(class, unload)("unloading class %s " INTPTR_FORMAT, ik->external_name(), p2i(ik));
2619   }
2620 
2621   Events::log_class_unloading(Thread::current(), ik);
2622 
2623 #if INCLUDE_JFR
2624   assert(ik != NULL, "invariant");
2625   EventClassUnload event;
2626   event.set_unloadedClass(ik);
2627   event.set_definingClassLoader(ik->class_loader_data());
2628   event.commit();
2629 #endif
2630 }
2631 
2632 void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {
2633   // Clean up C heap
2634   ik->release_C_heap_structures();
2635   ik->constants()->release_C_heap_structures();
2636 }
2637 
2638 void InstanceKlass::release_C_heap_structures() {
2639   // Can't release the constant pool here because the constant pool can be
2640   // deallocated separately from the InstanceKlass for default methods and
2641   // redefine classes.
2642 
2643   // Deallocate oop map cache
2644   if (_oop_map_cache != NULL) {
2645     delete _oop_map_cache;
2646     _oop_map_cache = NULL;
2647   }
2648 
2649   // Deallocate JNI identifiers for jfieldIDs
2650   JNIid::deallocate(jni_ids());
2651   set_jni_ids(NULL);
2652 
2653   jmethodID* jmeths = methods_jmethod_ids_acquire();
2654   if (jmeths != (jmethodID*)NULL) {
2655     release_set_methods_jmethod_ids(NULL);
2656     FreeHeap(jmeths);
2657   }
2658 
2659   assert(_dep_context == NULL,
2660          "dependencies should already be cleaned");
2661 
2662 #if INCLUDE_JVMTI
2663   // Deallocate breakpoint records
2664   if (breakpoints() != 0x0) {
2665     methods_do(clear_all_breakpoints);
2666     assert(breakpoints() == 0x0, "should have cleared breakpoints");
2667   }
2668 
2669   // deallocate the cached class file
2670   if (_cached_class_file != NULL) {
2671     os::free(_cached_class_file);
2672     _cached_class_file = NULL;
2673   }
2674 #endif
2675 
2676   // Decrement symbol reference counts associated with the unloaded class.
2677   if (_name != NULL) _name->decrement_refcount();
2678   // unreference array name derived from this class name (arrays of an unloaded
2679   // class can't be referenced anymore).
2680   if (_array_name != NULL)  _array_name->decrement_refcount();
2681   if (_value_types != NULL) {
2682     for (int i = 0; i < _value_types->length(); i++) {
2683       Symbol* s = _value_types->at(i)._class_name;
2684       if (s != NULL) {
2685         s->decrement_refcount();
2686       }
2687     }
2688   }
2689   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension);
2690 }
2691 
2692 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
2693   if (array == NULL) {
2694     _source_debug_extension = NULL;
2695   } else {
2696     // Adding one to the attribute length in order to store a null terminator
2697     // character could cause an overflow because the attribute length is
2698     // already coded with an u4 in the classfile, but in practice, it's
2699     // unlikely to happen.
2700     assert((length+1) > length, "Overflow checking");
2701     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2702     for (int i = 0; i < length; i++) {
2703       sde[i] = array[i];
2704     }
2705     sde[length] = '\0';
2706     _source_debug_extension = sde;
2707   }
2708 }
2709 
2710 const char* InstanceKlass::signature_name() const {
2711   return signature_name_of(is_value() ? 'Q' : 'L');
2712 }
2713 
2714 const char* InstanceKlass::signature_name_of(char c) const {
2715   int hash_len = 0;
2716   char hash_buf[40];
2717 
2718   // If this is an unsafe anonymous class, append a hash to make the name unique
2719   if (is_unsafe_anonymous()) {
2720     intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
2721     jio_snprintf(hash_buf, sizeof(hash_buf), "/" UINTX_FORMAT, (uintx)hash);
2722     hash_len = (int)strlen(hash_buf);
2723   }
2724 
2725   // Get the internal name as a c string
2726   const char* src = (const char*) (name()->as_C_string());
2727   const int src_length = (int)strlen(src);
2728 
2729   char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
2730 
2731   // Add L or Q as type indicator
2732   int dest_index = 0;
2733   dest[dest_index++] = c;
2734 
2735   // Add the actual class name
2736   for (int src_index = 0; src_index < src_length; ) {
2737     dest[dest_index++] = src[src_index++];
2738   }
2739 
2740   // If we have a hash, append it
2741   for (int hash_index = 0; hash_index < hash_len; ) {
2742     dest[dest_index++] = hash_buf[hash_index++];
2743   }
2744 
2745   // Add the semicolon and the NULL
2746   dest[dest_index++] = ';';
2747   dest[dest_index] = '\0';
2748   return dest;
2749 }
2750 
2751 // Used to obtain the package name from a fully qualified class name.
2752 Symbol* InstanceKlass::package_from_name(const Symbol* name, TRAPS) {
2753   if (name == NULL) {
2754     return NULL;
2755   } else {
2756     if (name->utf8_length() <= 0) {
2757       return NULL;
2758     }
2759     ResourceMark rm;
2760     const char* package_name = ClassLoader::package_from_name((const char*) name->as_C_string());
2761     if (package_name == NULL) {
2762       return NULL;
2763     }
2764     Symbol* pkg_name = SymbolTable::new_symbol(package_name);
2765     return pkg_name;
2766   }
2767 }
2768 
2769 ModuleEntry* InstanceKlass::module() const {
2770   // For an unsafe anonymous class return the host class' module
2771   if (is_unsafe_anonymous()) {
2772     assert(unsafe_anonymous_host() != NULL, "unsafe anonymous class must have a host class");
2773     return unsafe_anonymous_host()->module();
2774   }
2775 
2776   // Class is in a named package
2777   if (!in_unnamed_package()) {
2778     return _package_entry->module();
2779   }
2780 
2781   // Class is in an unnamed package, return its loader's unnamed module
2782   return class_loader_data()->unnamed_module();
2783 }
2784 
2785 void InstanceKlass::set_package(ClassLoaderData* loader_data, TRAPS) {
2786 
2787   // ensure java/ packages only loaded by boot or platform builtin loaders
2788   check_prohibited_package(name(), loader_data, CHECK);
2789 
2790   TempNewSymbol pkg_name = package_from_name(name(), CHECK);
2791 
2792   if (pkg_name != NULL && loader_data != NULL) {
2793 
2794     // Find in class loader's package entry table.
2795     _package_entry = loader_data->packages()->lookup_only(pkg_name);
2796 
2797     // If the package name is not found in the loader's package
2798     // entry table, it is an indication that the package has not
2799     // been defined. Consider it defined within the unnamed module.
2800     if (_package_entry == NULL) {
2801       ResourceMark rm;
2802 
2803       if (!ModuleEntryTable::javabase_defined()) {
2804         // Before java.base is defined during bootstrapping, define all packages in
2805         // the java.base module.  If a non-java.base package is erroneously placed
2806         // in the java.base module it will be caught later when java.base
2807         // is defined by ModuleEntryTable::verify_javabase_packages check.
2808         assert(ModuleEntryTable::javabase_moduleEntry() != NULL, JAVA_BASE_NAME " module is NULL");
2809         _package_entry = loader_data->packages()->lookup(pkg_name, ModuleEntryTable::javabase_moduleEntry());
2810       } else {
2811         assert(loader_data->unnamed_module() != NULL, "unnamed module is NULL");
2812         _package_entry = loader_data->packages()->lookup(pkg_name,
2813                                                          loader_data->unnamed_module());
2814       }
2815 
2816       // A package should have been successfully created
2817       assert(_package_entry != NULL, "Package entry for class %s not found, loader %s",
2818              name()->as_C_string(), loader_data->loader_name_and_id());
2819     }
2820 
2821     if (log_is_enabled(Debug, module)) {
2822       ResourceMark rm;
2823       ModuleEntry* m = _package_entry->module();
2824       log_trace(module)("Setting package: class: %s, package: %s, loader: %s, module: %s",
2825                         external_name(),
2826                         pkg_name->as_C_string(),
2827                         loader_data->loader_name_and_id(),
2828                         (m->is_named() ? m->name()->as_C_string() : UNNAMED_MODULE));
2829     }
2830   } else {
2831     ResourceMark rm;
2832     log_trace(module)("Setting package: class: %s, package: unnamed, loader: %s, module: %s",
2833                       external_name(),
2834                       (loader_data != NULL) ? loader_data->loader_name_and_id() : "NULL",
2835                       UNNAMED_MODULE);
2836   }
2837 }
2838 
2839 
2840 // different versions of is_same_class_package
2841 
2842 bool InstanceKlass::is_same_class_package(const Klass* class2) const {
2843   oop classloader1 = this->class_loader();
2844   PackageEntry* classpkg1 = this->package();
2845   if (class2->is_objArray_klass()) {
2846     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
2847   }
2848 
2849   oop classloader2;
2850   PackageEntry* classpkg2;
2851   if (class2->is_instance_klass()) {
2852     classloader2 = class2->class_loader();
2853     classpkg2 = class2->package();
2854   } else {
2855     assert(class2->is_typeArray_klass(), "should be type array");
2856     classloader2 = NULL;
2857     classpkg2 = NULL;
2858   }
2859 
2860   // Same package is determined by comparing class loader
2861   // and package entries. Both must be the same. This rule
2862   // applies even to classes that are defined in the unnamed
2863   // package, they still must have the same class loader.
2864   if (oopDesc::equals(classloader1, classloader2) && (classpkg1 == classpkg2)) {
2865     return true;
2866   }
2867 
2868   return false;
2869 }
2870 
2871 // return true if this class and other_class are in the same package. Classloader
2872 // and classname information is enough to determine a class's package
2873 bool InstanceKlass::is_same_class_package(oop other_class_loader,
2874                                           const Symbol* other_class_name) const {
2875   if (!oopDesc::equals(class_loader(), other_class_loader)) {
2876     return false;
2877   }
2878   if (name()->fast_compare(other_class_name) == 0) {
2879      return true;
2880   }
2881 
2882   {
2883     ResourceMark rm;
2884 
2885     bool bad_class_name = false;
2886     const char* other_pkg =
2887       ClassLoader::package_from_name((const char*) other_class_name->as_C_string(), &bad_class_name);
2888     if (bad_class_name) {
2889       return false;
2890     }
2891     // Check that package_from_name() returns NULL, not "", if there is no package.
2892     assert(other_pkg == NULL || strlen(other_pkg) > 0, "package name is empty string");
2893 
2894     const Symbol* const this_package_name =
2895       this->package() != NULL ? this->package()->name() : NULL;
2896 
2897     if (this_package_name == NULL || other_pkg == NULL) {
2898       // One of the two doesn't have a package.  Only return true if the other
2899       // one also doesn't have a package.
2900       return (const char*)this_package_name == other_pkg;
2901     }
2902 
2903     // Check if package is identical
2904     return this_package_name->equals(other_pkg);
2905   }
2906 }
2907 
2908 // Returns true iff super_method can be overridden by a method in targetclassname
2909 // See JLS 3rd edition 8.4.6.1
2910 // Assumes name-signature match
2911 // "this" is InstanceKlass of super_method which must exist
2912 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
2913 bool InstanceKlass::is_override(const methodHandle& super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
2914    // Private methods can not be overridden
2915    if (super_method->is_private()) {
2916      return false;
2917    }
2918    // If super method is accessible, then override
2919    if ((super_method->is_protected()) ||
2920        (super_method->is_public())) {
2921      return true;
2922    }
2923    // Package-private methods are not inherited outside of package
2924    assert(super_method->is_package_private(), "must be package private");
2925    return(is_same_class_package(targetclassloader(), targetclassname));
2926 }
2927 
2928 // Only boot and platform class loaders can define classes in "java/" packages.
2929 void InstanceKlass::check_prohibited_package(Symbol* class_name,
2930                                              ClassLoaderData* loader_data,
2931                                              TRAPS) {
2932   if (!loader_data->is_boot_class_loader_data() &&
2933       !loader_data->is_platform_class_loader_data() &&
2934       class_name != NULL) {
2935     ResourceMark rm(THREAD);
2936     char* name = class_name->as_C_string();
2937     if (strncmp(name, JAVAPKG, JAVAPKG_LEN) == 0 && name[JAVAPKG_LEN] == '/') {
2938       TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK);
2939       assert(pkg_name != NULL, "Error in parsing package name starting with 'java/'");
2940       name = pkg_name->as_C_string();
2941       const char* class_loader_name = loader_data->loader_name_and_id();
2942       StringUtils::replace_no_expand(name, "/", ".");
2943       const char* msg_text1 = "Class loader (instance of): ";
2944       const char* msg_text2 = " tried to load prohibited package name: ";
2945       size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + strlen(name) + 1;
2946       char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len);
2947       jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, name);
2948       THROW_MSG(vmSymbols::java_lang_SecurityException(), message);
2949     }
2950   }
2951   return;
2952 }
2953 
2954 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
2955   constantPoolHandle i_cp(THREAD, constants());
2956   for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
2957     int ioff = iter.inner_class_info_index();
2958     if (ioff != 0) {
2959       // Check to see if the name matches the class we're looking for
2960       // before attempting to find the class.
2961       if (i_cp->klass_name_at_matches(this, ioff)) {
2962         Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
2963         if (this == inner_klass) {
2964           *ooff = iter.outer_class_info_index();
2965           *noff = iter.inner_name_index();
2966           return true;
2967         }
2968       }
2969     }
2970   }
2971   return false;
2972 }
2973 
2974 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
2975   InstanceKlass* outer_klass = NULL;
2976   *inner_is_member = false;
2977   int ooff = 0, noff = 0;
2978   bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
2979   if (has_inner_classes_attr) {
2980     constantPoolHandle i_cp(THREAD, constants());
2981     if (ooff != 0) {
2982       Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
2983       outer_klass = InstanceKlass::cast(ok);
2984       *inner_is_member = true;
2985     }
2986     if (NULL == outer_klass) {
2987       // It may be unsafe anonymous; try for that.
2988       int encl_method_class_idx = enclosing_method_class_index();
2989       if (encl_method_class_idx != 0) {
2990         Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
2991         outer_klass = InstanceKlass::cast(ok);
2992         *inner_is_member = false;
2993       }
2994     }
2995   }
2996 
2997   // If no inner class attribute found for this class.
2998   if (NULL == outer_klass) return NULL;
2999 
3000   // Throws an exception if outer klass has not declared k as an inner klass
3001   // We need evidence that each klass knows about the other, or else
3002   // the system could allow a spoof of an inner class to gain access rights.
3003   Reflection::check_for_inner_class(outer_klass, this, *inner_is_member, CHECK_NULL);
3004   return outer_klass;
3005 }
3006 
3007 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
3008   jint access = access_flags().as_int();
3009 
3010   // But check if it happens to be member class.
3011   InnerClassesIterator iter(this);
3012   for (; !iter.done(); iter.next()) {
3013     int ioff = iter.inner_class_info_index();
3014     // Inner class attribute can be zero, skip it.
3015     // Strange but true:  JVM spec. allows null inner class refs.
3016     if (ioff == 0) continue;
3017 
3018     // only look at classes that are already loaded
3019     // since we are looking for the flags for our self.
3020     Symbol* inner_name = constants()->klass_name_at(ioff);
3021     if (name() == inner_name) {
3022       // This is really a member class.
3023       access = iter.inner_access_flags();
3024       break;
3025     }
3026   }
3027   // Remember to strip ACC_SUPER bit
3028   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
3029 }
3030 
3031 jint InstanceKlass::jvmti_class_status() const {
3032   jint result = 0;
3033 
3034   if (is_linked()) {
3035     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3036   }
3037 
3038   if (is_initialized()) {
3039     assert(is_linked(), "Class status is not consistent");
3040     result |= JVMTI_CLASS_STATUS_INITIALIZED;
3041   }
3042   if (is_in_error_state()) {
3043     result |= JVMTI_CLASS_STATUS_ERROR;
3044   }
3045   return result;
3046 }
3047 
3048 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
3049   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
3050   int method_table_offset_in_words = ioe->offset()/wordSize;
3051   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
3052                        / itableOffsetEntry::size();
3053 
3054   for (int cnt = 0 ; ; cnt ++, ioe ++) {
3055     // If the interface isn't implemented by the receiver class,
3056     // the VM should throw IncompatibleClassChangeError.
3057     if (cnt >= nof_interfaces) {
3058       ResourceMark rm(THREAD);
3059       stringStream ss;
3060       bool same_module = (module() == holder->module());
3061       ss.print("Receiver class %s does not implement "
3062                "the interface %s defining the method to be called "
3063                "(%s%s%s)",
3064                external_name(), holder->external_name(),
3065                (same_module) ? joint_in_module_of_loader(holder) : class_in_module_of_loader(),
3066                (same_module) ? "" : "; ",
3067                (same_module) ? "" : holder->class_in_module_of_loader());
3068       THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
3069     }
3070 
3071     Klass* ik = ioe->interface_klass();
3072     if (ik == holder) break;
3073   }
3074 
3075   itableMethodEntry* ime = ioe->first_method_entry(this);
3076   Method* m = ime[index].method();
3077   if (m == NULL) {
3078     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
3079   }
3080   return m;
3081 }
3082 
3083 
3084 #if INCLUDE_JVMTI
3085 // update default_methods for redefineclasses for methods that are
3086 // not yet in the vtable due to concurrent subclass define and superinterface
3087 // redefinition
3088 // Note: those in the vtable, should have been updated via adjust_method_entries
3089 void InstanceKlass::adjust_default_methods(bool* trace_name_printed) {
3090   // search the default_methods for uses of either obsolete or EMCP methods
3091   if (default_methods() != NULL) {
3092     for (int index = 0; index < default_methods()->length(); index ++) {
3093       Method* old_method = default_methods()->at(index);
3094       if (old_method == NULL || !old_method->is_old()) {
3095         continue; // skip uninteresting entries
3096       }
3097       assert(!old_method->is_deleted(), "default methods may not be deleted");
3098       Method* new_method = old_method->get_new_method();
3099       default_methods()->at_put(index, new_method);
3100 
3101       if (log_is_enabled(Info, redefine, class, update)) {
3102         ResourceMark rm;
3103         if (!(*trace_name_printed)) {
3104           log_info(redefine, class, update)
3105             ("adjust: klassname=%s default methods from name=%s",
3106              external_name(), old_method->method_holder()->external_name());
3107           *trace_name_printed = true;
3108         }
3109         log_debug(redefine, class, update, vtables)
3110           ("default method update: %s(%s) ",
3111            new_method->name()->as_C_string(), new_method->signature()->as_C_string());
3112       }
3113     }
3114   }
3115 }
3116 #endif // INCLUDE_JVMTI
3117 
3118 // On-stack replacement stuff
3119 void InstanceKlass::add_osr_nmethod(nmethod* n) {
3120 #ifndef PRODUCT
3121   if (TieredCompilation) {
3122       nmethod * prev = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), n->comp_level(), true);
3123       assert(prev == NULL || !prev->is_in_use(),
3124       "redundunt OSR recompilation detected. memory leak in CodeCache!");
3125   }
3126 #endif
3127   // only one compilation can be active
3128   {
3129     // This is a short non-blocking critical region, so the no safepoint check is ok.
3130     MutexLocker ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
3131     assert(n->is_osr_method(), "wrong kind of nmethod");
3132     n->set_osr_link(osr_nmethods_head());
3133     set_osr_nmethods_head(n);
3134     // Raise the highest osr level if necessary
3135     if (TieredCompilation) {
3136       Method* m = n->method();
3137       m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
3138     }
3139   }
3140 
3141   // Get rid of the osr methods for the same bci that have lower levels.
3142   if (TieredCompilation) {
3143     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
3144       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
3145       if (inv != NULL && inv->is_in_use()) {
3146         inv->make_not_entrant();
3147       }
3148     }
3149   }
3150 }
3151 
3152 // Remove osr nmethod from the list. Return true if found and removed.
3153 bool InstanceKlass::remove_osr_nmethod(nmethod* n) {
3154   // This is a short non-blocking critical region, so the no safepoint check is ok.
3155   MutexLocker ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
3156   assert(n->is_osr_method(), "wrong kind of nmethod");
3157   nmethod* last = NULL;
3158   nmethod* cur  = osr_nmethods_head();
3159   int max_level = CompLevel_none;  // Find the max comp level excluding n
3160   Method* m = n->method();
3161   // Search for match
3162   bool found = false;
3163   while(cur != NULL && cur != n) {
3164     if (TieredCompilation && m == cur->method()) {
3165       // Find max level before n
3166       max_level = MAX2(max_level, cur->comp_level());
3167     }
3168     last = cur;
3169     cur = cur->osr_link();
3170   }
3171   nmethod* next = NULL;
3172   if (cur == n) {
3173     found = true;
3174     next = cur->osr_link();
3175     if (last == NULL) {
3176       // Remove first element
3177       set_osr_nmethods_head(next);
3178     } else {
3179       last->set_osr_link(next);
3180     }
3181   }
3182   n->set_osr_link(NULL);
3183   if (TieredCompilation) {
3184     cur = next;
3185     while (cur != NULL) {
3186       // Find max level after n
3187       if (m == cur->method()) {
3188         max_level = MAX2(max_level, cur->comp_level());
3189       }
3190       cur = cur->osr_link();
3191     }
3192     m->set_highest_osr_comp_level(max_level);
3193   }
3194   return found;
3195 }
3196 
3197 int InstanceKlass::mark_osr_nmethods(const Method* m) {
3198   // This is a short non-blocking critical region, so the no safepoint check is ok.
3199   MutexLocker ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
3200   nmethod* osr = osr_nmethods_head();
3201   int found = 0;
3202   while (osr != NULL) {
3203     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3204     if (osr->method() == m) {
3205       osr->mark_for_deoptimization();
3206       found++;
3207     }
3208     osr = osr->osr_link();
3209   }
3210   return found;
3211 }
3212 
3213 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
3214   // This is a short non-blocking critical region, so the no safepoint check is ok.
3215   MutexLocker ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
3216   nmethod* osr = osr_nmethods_head();
3217   nmethod* best = NULL;
3218   while (osr != NULL) {
3219     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3220     // There can be a time when a c1 osr method exists but we are waiting
3221     // for a c2 version. When c2 completes its osr nmethod we will trash
3222     // the c1 version and only be able to find the c2 version. However
3223     // while we overflow in the c1 code at back branches we don't want to
3224     // try and switch to the same code as we are already running
3225 
3226     if (osr->method() == m &&
3227         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
3228       if (match_level) {
3229         if (osr->comp_level() == comp_level) {
3230           // Found a match - return it.
3231           return osr;
3232         }
3233       } else {
3234         if (best == NULL || (osr->comp_level() > best->comp_level())) {
3235           if (osr->comp_level() == CompLevel_highest_tier) {
3236             // Found the best possible - return it.
3237             return osr;
3238           }
3239           best = osr;
3240         }
3241       }
3242     }
3243     osr = osr->osr_link();
3244   }
3245 
3246   assert(match_level == false || best == NULL, "shouldn't pick up anything if match_level is set");
3247   if (best != NULL && best->comp_level() >= comp_level) {
3248     return best;
3249   }
3250   return NULL;
3251 }
3252 
3253 // -----------------------------------------------------------------------------------------------------
3254 // Printing
3255 
3256 #ifndef PRODUCT
3257 
3258 #define BULLET  " - "
3259 
3260 static const char* state_names[] = {
3261   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3262 };
3263 
3264 static void print_vtable(address self, intptr_t* start, int len, outputStream* st) {
3265   ResourceMark rm;
3266   int* forward_refs = NEW_RESOURCE_ARRAY(int, len);
3267   for (int i = 0; i < len; i++)  forward_refs[i] = 0;
3268   for (int i = 0; i < len; i++) {
3269     intptr_t e = start[i];
3270     st->print("%d : " INTPTR_FORMAT, i, e);
3271     if (forward_refs[i] != 0) {
3272       int from = forward_refs[i];
3273       int off = (int) start[from];
3274       st->print(" (offset %d <= [%d])", off, from);
3275     }
3276     if (MetaspaceObj::is_valid((Metadata*)e)) {
3277       st->print(" ");
3278       ((Metadata*)e)->print_value_on(st);
3279     } else if (self != NULL && e > 0 && e < 0x10000) {
3280       address location = self + e;
3281       int index = (int)((intptr_t*)location - start);
3282       st->print(" (offset %d => [%d])", (int)e, index);
3283       if (index >= 0 && index < len)
3284         forward_refs[index] = i;
3285     }
3286     st->cr();
3287   }
3288 }
3289 
3290 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3291   return print_vtable(NULL, reinterpret_cast<intptr_t*>(start), len, st);
3292 }
3293 
3294 template<typename T>
3295  static void print_array_on(outputStream* st, Array<T>* array) {
3296    if (array == NULL) { st->print_cr("NULL"); return; }
3297    array->print_value_on(st); st->cr();
3298    if (Verbose || WizardMode) {
3299      for (int i = 0; i < array->length(); i++) {
3300        st->print("%d : ", i); array->at(i)->print_value_on(st); st->cr();
3301      }
3302    }
3303  }
3304 
3305 static void print_array_on(outputStream* st, Array<int>* array) {
3306   if (array == NULL) { st->print_cr("NULL"); return; }
3307   array->print_value_on(st); st->cr();
3308   if (Verbose || WizardMode) {
3309     for (int i = 0; i < array->length(); i++) {
3310       st->print("%d : %d", i, array->at(i)); st->cr();
3311     }
3312   }
3313 }
3314 
3315 void InstanceKlass::print_on(outputStream* st) const {
3316   assert(is_klass(), "must be klass");
3317   Klass::print_on(st);
3318 
3319   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3320   st->print(BULLET"klass size:        %d", size());                               st->cr();
3321   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
3322   st->print(BULLET"misc flags:        0x%x", _misc_flags);                        st->cr();
3323   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
3324   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3325   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3326   st->print(BULLET"sub:               ");
3327   Klass* sub = subklass();
3328   int n;
3329   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
3330     if (n < MaxSubklassPrintSize) {
3331       sub->print_value_on(st);
3332       st->print("   ");
3333     }
3334   }
3335   if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize);
3336   st->cr();
3337 
3338   if (is_interface()) {
3339     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
3340     if (nof_implementors() == 1) {
3341       st->print_cr(BULLET"implementor:    ");
3342       st->print("   ");
3343       implementor()->print_value_on(st);
3344       st->cr();
3345     }
3346   }
3347 
3348   st->print(BULLET"arrays:            "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3349   st->print(BULLET"methods:           "); print_array_on(st, methods());
3350   st->print(BULLET"method ordering:   "); print_array_on(st, method_ordering());
3351   st->print(BULLET"default_methods:   "); print_array_on(st, default_methods());
3352   if (default_vtable_indices() != NULL) {
3353     st->print(BULLET"default vtable indices:   "); print_array_on(st, default_vtable_indices());
3354   }
3355   st->print(BULLET"local interfaces:  "); print_array_on(st, local_interfaces());
3356   st->print(BULLET"trans. interfaces: "); print_array_on(st, transitive_interfaces());
3357   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
3358   if (class_loader_data() != NULL) {
3359     st->print(BULLET"class loader data:  ");
3360     class_loader_data()->print_value_on(st);
3361     st->cr();
3362   }
3363   st->print(BULLET"unsafe anonymous host class:        "); Metadata::print_value_on_maybe_null(st, unsafe_anonymous_host()); st->cr();
3364   if (source_file_name() != NULL) {
3365     st->print(BULLET"source file:       ");
3366     source_file_name()->print_value_on(st);
3367     st->cr();
3368   }
3369   if (source_debug_extension() != NULL) {
3370     st->print(BULLET"source debug extension:       ");
3371     st->print("%s", source_debug_extension());
3372     st->cr();
3373   }
3374   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
3375   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
3376   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
3377   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
3378   {
3379     bool have_pv = false;
3380     // previous versions are linked together through the InstanceKlass
3381     for (InstanceKlass* pv_node = previous_versions();
3382          pv_node != NULL;
3383          pv_node = pv_node->previous_versions()) {
3384       if (!have_pv)
3385         st->print(BULLET"previous version:  ");
3386       have_pv = true;
3387       pv_node->constants()->print_value_on(st);
3388     }
3389     if (have_pv) st->cr();
3390   }
3391 
3392   if (generic_signature() != NULL) {
3393     st->print(BULLET"generic signature: ");
3394     generic_signature()->print_value_on(st);
3395     st->cr();
3396   }
3397   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
3398   st->print(BULLET"nest members:     "); nest_members()->print_value_on(st);     st->cr();
3399   if (java_mirror() != NULL) {
3400     st->print(BULLET"java mirror:       ");
3401     java_mirror()->print_value_on(st);
3402     st->cr();
3403   } else {
3404     st->print_cr(BULLET"java mirror:       NULL");
3405   }
3406   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3407   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
3408   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3409   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(NULL, start_of_itable(), itable_length(), st);
3410   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3411   FieldPrinter print_static_field(st);
3412   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3413   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3414   FieldPrinter print_nonstatic_field(st);
3415   InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3416   ik->do_nonstatic_fields(&print_nonstatic_field);
3417 
3418   st->print(BULLET"non-static oop maps: ");
3419   OopMapBlock* map     = start_of_nonstatic_oop_maps();
3420   OopMapBlock* end_map = map + nonstatic_oop_map_count();
3421   while (map < end_map) {
3422     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3423     map++;
3424   }
3425   st->cr();
3426 }
3427 
3428 #endif //PRODUCT
3429 
3430 void InstanceKlass::print_value_on(outputStream* st) const {
3431   assert(is_klass(), "must be klass");
3432   if (Verbose || WizardMode)  access_flags().print_on(st);
3433   name()->print_value_on(st);
3434 }
3435 
3436 #ifndef PRODUCT
3437 
3438 void FieldPrinter::do_field(fieldDescriptor* fd) {
3439   _st->print(BULLET);
3440    if (_obj == NULL) {
3441      fd->print_on(_st);
3442      _st->cr();
3443    } else {
3444      fd->print_on_for(_st, _obj);
3445      _st->cr();
3446    }
3447 }
3448 
3449 
3450 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3451   Klass::oop_print_on(obj, st);
3452 
3453   if (this == SystemDictionary::String_klass()) {
3454     typeArrayOop value  = java_lang_String::value(obj);
3455     juint        length = java_lang_String::length(obj);
3456     if (value != NULL &&
3457         value->is_typeArray() &&
3458         length <= (juint) value->length()) {
3459       st->print(BULLET"string: ");
3460       java_lang_String::print(obj, st);
3461       st->cr();
3462       if (!WizardMode)  return;  // that is enough
3463     }
3464   }
3465 
3466   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
3467   FieldPrinter print_field(st, obj);
3468   do_nonstatic_fields(&print_field);
3469 
3470   if (this == SystemDictionary::Class_klass()) {
3471     st->print(BULLET"signature: ");
3472     java_lang_Class::print_signature(obj, st);
3473     st->cr();
3474     Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
3475     st->print(BULLET"fake entry for mirror: ");
3476     Metadata::print_value_on_maybe_null(st, mirrored_klass);
3477     st->cr();
3478     Klass* array_klass = java_lang_Class::array_klass_acquire(obj);
3479     st->print(BULLET"fake entry for array: ");
3480     Metadata::print_value_on_maybe_null(st, array_klass);
3481     st->cr();
3482     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
3483     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
3484     Klass* real_klass = java_lang_Class::as_Klass(obj);
3485     if (real_klass != NULL && real_klass->is_instance_klass()) {
3486       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3487     }
3488   } else if (this == SystemDictionary::MethodType_klass()) {
3489     st->print(BULLET"signature: ");
3490     java_lang_invoke_MethodType::print_signature(obj, st);
3491     st->cr();
3492   }
3493 }
3494 
3495 bool InstanceKlass::verify_itable_index(int i) {
3496   int method_count = klassItable::method_count_for_interface(this);
3497   assert(i >= 0 && i < method_count, "index out of bounds");
3498   return true;
3499 }
3500 
3501 #endif //PRODUCT
3502 
3503 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
3504   st->print("a ");
3505   name()->print_value_on(st);
3506   obj->print_address_on(st);
3507   if (this == SystemDictionary::String_klass()
3508       && java_lang_String::value(obj) != NULL) {
3509     ResourceMark rm;
3510     int len = java_lang_String::length(obj);
3511     int plen = (len < 24 ? len : 12);
3512     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
3513     st->print(" = \"%s\"", str);
3514     if (len > plen)
3515       st->print("...[%d]", len);
3516   } else if (this == SystemDictionary::Class_klass()) {
3517     Klass* k = java_lang_Class::as_Klass(obj);
3518     st->print(" = ");
3519     if (k != NULL) {
3520       k->print_value_on(st);
3521     } else {
3522       const char* tname = type2name(java_lang_Class::primitive_type(obj));
3523       st->print("%s", tname ? tname : "type?");
3524     }
3525   } else if (this == SystemDictionary::MethodType_klass()) {
3526     st->print(" = ");
3527     java_lang_invoke_MethodType::print_signature(obj, st);
3528   } else if (java_lang_boxing_object::is_instance(obj)) {
3529     st->print(" = ");
3530     java_lang_boxing_object::print(obj, st);
3531   } else if (this == SystemDictionary::LambdaForm_klass()) {
3532     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
3533     if (vmentry != NULL) {
3534       st->print(" => ");
3535       vmentry->print_value_on(st);
3536     }
3537   } else if (this == SystemDictionary::MemberName_klass()) {
3538     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
3539     if (vmtarget != NULL) {
3540       st->print(" = ");
3541       vmtarget->print_value_on(st);
3542     } else {
3543       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
3544       st->print(".");
3545       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
3546     }
3547   }
3548 }
3549 
3550 const char* InstanceKlass::internal_name() const {
3551   return external_name();
3552 }
3553 
3554 void InstanceKlass::print_class_load_logging(ClassLoaderData* loader_data,
3555                                              const char* module_name,
3556                                              const ClassFileStream* cfs) const {
3557   if (!log_is_enabled(Info, class, load)) {
3558     return;
3559   }
3560 
3561   ResourceMark rm;
3562   LogMessage(class, load) msg;
3563   stringStream info_stream;
3564 
3565   // Name and class hierarchy info
3566   info_stream.print("%s", external_name());
3567 
3568   // Source
3569   if (cfs != NULL) {
3570     if (cfs->source() != NULL) {
3571       if (module_name != NULL) {
3572         // When the boot loader created the stream, it didn't know the module name
3573         // yet. Let's format it now.
3574         if (cfs->from_boot_loader_modules_image()) {
3575           info_stream.print(" source: jrt:/%s", module_name);
3576         } else {
3577           info_stream.print(" source: %s", cfs->source());
3578         }
3579       } else {
3580         info_stream.print(" source: %s", cfs->source());
3581       }
3582     } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) {
3583       Thread* THREAD = Thread::current();
3584       Klass* caller =
3585             THREAD->is_Java_thread()
3586                 ? ((JavaThread*)THREAD)->security_get_caller_class(1)
3587                 : NULL;
3588       // caller can be NULL, for example, during a JVMTI VM_Init hook
3589       if (caller != NULL) {
3590         info_stream.print(" source: instance of %s", caller->external_name());
3591       } else {
3592         // source is unknown
3593       }
3594     } else {
3595       oop class_loader = loader_data->class_loader();
3596       info_stream.print(" source: %s", class_loader->klass()->external_name());
3597     }
3598   } else {
3599     assert(this->is_shared(), "must be");
3600     if (MetaspaceShared::is_shared_dynamic((void*)this)) {
3601       info_stream.print(" source: shared objects file (top)");
3602     } else {
3603       info_stream.print(" source: shared objects file");
3604     }
3605   }
3606 
3607   msg.info("%s", info_stream.as_string());
3608 
3609   if (log_is_enabled(Debug, class, load)) {
3610     stringStream debug_stream;
3611 
3612     // Class hierarchy info
3613     debug_stream.print(" klass: " INTPTR_FORMAT " super: " INTPTR_FORMAT,
3614                        p2i(this),  p2i(superklass()));
3615 
3616     // Interfaces
3617     if (local_interfaces() != NULL && local_interfaces()->length() > 0) {
3618       debug_stream.print(" interfaces:");
3619       int length = local_interfaces()->length();
3620       for (int i = 0; i < length; i++) {
3621         debug_stream.print(" " INTPTR_FORMAT,
3622                            p2i(InstanceKlass::cast(local_interfaces()->at(i))));
3623       }
3624     }
3625 
3626     // Class loader
3627     debug_stream.print(" loader: [");
3628     loader_data->print_value_on(&debug_stream);
3629     debug_stream.print("]");
3630 
3631     // Classfile checksum
3632     if (cfs) {
3633       debug_stream.print(" bytes: %d checksum: %08x",
3634                          cfs->length(),
3635                          ClassLoader::crc32(0, (const char*)cfs->buffer(),
3636                          cfs->length()));
3637     }
3638 
3639     msg.debug("%s", debug_stream.as_string());
3640   }
3641 }
3642 
3643 #if INCLUDE_SERVICES
3644 // Size Statistics
3645 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
3646   Klass::collect_statistics(sz);
3647 
3648   sz->_inst_size  = wordSize * size_helper();
3649   sz->_vtab_bytes = wordSize * vtable_length();
3650   sz->_itab_bytes = wordSize * itable_length();
3651   sz->_nonstatic_oopmap_bytes = wordSize * nonstatic_oop_map_size();
3652 
3653   int n = 0;
3654   n += (sz->_methods_array_bytes         = sz->count_array(methods()));
3655   n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
3656   n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
3657   n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
3658   n += (sz->_fields_bytes                = sz->count_array(fields()));
3659   n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
3660   n += (sz->_nest_members_bytes          = sz->count_array(nest_members()));
3661   sz->_ro_bytes += n;
3662 
3663   const ConstantPool* cp = constants();
3664   if (cp) {
3665     cp->collect_statistics(sz);
3666   }
3667 
3668   const Annotations* anno = annotations();
3669   if (anno) {
3670     anno->collect_statistics(sz);
3671   }
3672 
3673   const Array<Method*>* methods_array = methods();
3674   if (methods()) {
3675     for (int i = 0; i < methods_array->length(); i++) {
3676       Method* method = methods_array->at(i);
3677       if (method) {
3678         sz->_method_count ++;
3679         method->collect_statistics(sz);
3680       }
3681     }
3682   }
3683 }
3684 #endif // INCLUDE_SERVICES
3685 
3686 // Verification
3687 
3688 class VerifyFieldClosure: public BasicOopIterateClosure {
3689  protected:
3690   template <class T> void do_oop_work(T* p) {
3691     oop obj = RawAccess<>::oop_load(p);
3692     if (!oopDesc::is_oop_or_null(obj)) {
3693       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj));
3694       Universe::print_on(tty);
3695       guarantee(false, "boom");
3696     }
3697   }
3698  public:
3699   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
3700   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
3701 };
3702 
3703 void InstanceKlass::verify_on(outputStream* st) {
3704 #ifndef PRODUCT
3705   // Avoid redundant verifies, this really should be in product.
3706   if (_verify_count == Universe::verify_count()) return;
3707   _verify_count = Universe::verify_count();
3708 #endif
3709 
3710   // Verify Klass
3711   Klass::verify_on(st);
3712 
3713   // Verify that klass is present in ClassLoaderData
3714   guarantee(class_loader_data()->contains_klass(this),
3715             "this class isn't found in class loader data");
3716 
3717   // Verify vtables
3718   if (is_linked()) {
3719     // $$$ This used to be done only for m/s collections.  Doing it
3720     // always seemed a valid generalization.  (DLD -- 6/00)
3721     vtable().verify(st);
3722   }
3723 
3724   // Verify first subklass
3725   if (subklass() != NULL) {
3726     guarantee(subklass()->is_klass(), "should be klass");
3727   }
3728 
3729   // Verify siblings
3730   Klass* super = this->super();
3731   Klass* sib = next_sibling();
3732   if (sib != NULL) {
3733     if (sib == this) {
3734       fatal("subclass points to itself " PTR_FORMAT, p2i(sib));
3735     }
3736 
3737     guarantee(sib->is_klass(), "should be klass");
3738     guarantee(sib->super() == super, "siblings should have same superklass");
3739   }
3740 
3741   // Verify local interfaces
3742   if (local_interfaces()) {
3743     Array<InstanceKlass*>* local_interfaces = this->local_interfaces();
3744     for (int j = 0; j < local_interfaces->length(); j++) {
3745       InstanceKlass* e = local_interfaces->at(j);
3746       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
3747     }
3748   }
3749 
3750   // Verify transitive interfaces
3751   if (transitive_interfaces() != NULL) {
3752     Array<InstanceKlass*>* transitive_interfaces = this->transitive_interfaces();
3753     for (int j = 0; j < transitive_interfaces->length(); j++) {
3754       InstanceKlass* e = transitive_interfaces->at(j);
3755       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
3756     }
3757   }
3758 
3759   // Verify methods
3760   if (methods() != NULL) {
3761     Array<Method*>* methods = this->methods();
3762     for (int j = 0; j < methods->length(); j++) {
3763       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3764     }
3765     for (int j = 0; j < methods->length() - 1; j++) {
3766       Method* m1 = methods->at(j);
3767       Method* m2 = methods->at(j + 1);
3768       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3769     }
3770   }
3771 
3772   // Verify method ordering
3773   if (method_ordering() != NULL) {
3774     Array<int>* method_ordering = this->method_ordering();
3775     int length = method_ordering->length();
3776     if (JvmtiExport::can_maintain_original_method_order() ||
3777         ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
3778       guarantee(length == methods()->length(), "invalid method ordering length");
3779       jlong sum = 0;
3780       for (int j = 0; j < length; j++) {
3781         int original_index = method_ordering->at(j);
3782         guarantee(original_index >= 0, "invalid method ordering index");
3783         guarantee(original_index < length, "invalid method ordering index");
3784         sum += original_index;
3785       }
3786       // Verify sum of indices 0,1,...,length-1
3787       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
3788     } else {
3789       guarantee(length == 0, "invalid method ordering length");
3790     }
3791   }
3792 
3793   // Verify default methods
3794   if (default_methods() != NULL) {
3795     Array<Method*>* methods = this->default_methods();
3796     for (int j = 0; j < methods->length(); j++) {
3797       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3798     }
3799     for (int j = 0; j < methods->length() - 1; j++) {
3800       Method* m1 = methods->at(j);
3801       Method* m2 = methods->at(j + 1);
3802       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3803     }
3804   }
3805 
3806   // Verify JNI static field identifiers
3807   if (jni_ids() != NULL) {
3808     jni_ids()->verify(this);
3809   }
3810 
3811   // Verify other fields
3812   if (array_klasses() != NULL) {
3813     guarantee(array_klasses()->is_klass(), "should be klass");
3814   }
3815   if (constants() != NULL) {
3816     guarantee(constants()->is_constantPool(), "should be constant pool");
3817   }
3818   const Klass* anonymous_host = unsafe_anonymous_host();
3819   if (anonymous_host != NULL) {
3820     guarantee(anonymous_host->is_klass(), "should be klass");
3821   }
3822 }
3823 
3824 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
3825   Klass::oop_verify_on(obj, st);
3826   VerifyFieldClosure blk;
3827   obj->oop_iterate(&blk);
3828 }
3829 
3830 
3831 // JNIid class for jfieldIDs only
3832 // Note to reviewers:
3833 // These JNI functions are just moved over to column 1 and not changed
3834 // in the compressed oops workspace.
3835 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
3836   _holder = holder;
3837   _offset = offset;
3838   _next = next;
3839   debug_only(_is_static_field_id = false;)
3840 }
3841 
3842 
3843 JNIid* JNIid::find(int offset) {
3844   JNIid* current = this;
3845   while (current != NULL) {
3846     if (current->offset() == offset) return current;
3847     current = current->next();
3848   }
3849   return NULL;
3850 }
3851 
3852 void JNIid::deallocate(JNIid* current) {
3853   while (current != NULL) {
3854     JNIid* next = current->next();
3855     delete current;
3856     current = next;
3857   }
3858 }
3859 
3860 
3861 void JNIid::verify(Klass* holder) {
3862   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
3863   int end_field_offset;
3864   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
3865 
3866   JNIid* current = this;
3867   while (current != NULL) {
3868     guarantee(current->holder() == holder, "Invalid klass in JNIid");
3869 #ifdef ASSERT
3870     int o = current->offset();
3871     if (current->is_static_field_id()) {
3872       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
3873     }
3874 #endif
3875     current = current->next();
3876   }
3877 }
3878 
3879 void InstanceKlass::set_init_state(ClassState state) {
3880 #ifdef ASSERT
3881   bool good_state = is_shared() ? (_init_state <= state)
3882                                                : (_init_state < state);
3883   assert(good_state || state == allocated, "illegal state transition");
3884 #endif
3885   assert(_init_thread == NULL, "should be cleared before state change");
3886   _init_state = (u1)state;
3887 }
3888 
3889 #if INCLUDE_JVMTI
3890 
3891 // RedefineClasses() support for previous versions
3892 
3893 // Globally, there is at least one previous version of a class to walk
3894 // during class unloading, which is saved because old methods in the class
3895 // are still running.   Otherwise the previous version list is cleaned up.
3896 bool InstanceKlass::_has_previous_versions = false;
3897 
3898 // Returns true if there are previous versions of a class for class
3899 // unloading only. Also resets the flag to false. purge_previous_version
3900 // will set the flag to true if there are any left, i.e., if there's any
3901 // work to do for next time. This is to avoid the expensive code cache
3902 // walk in CLDG::clean_deallocate_lists().
3903 bool InstanceKlass::has_previous_versions_and_reset() {
3904   bool ret = _has_previous_versions;
3905   log_trace(redefine, class, iklass, purge)("Class unloading: has_previous_versions = %s",
3906      ret ? "true" : "false");
3907   _has_previous_versions = false;
3908   return ret;
3909 }
3910 
3911 // Purge previous versions before adding new previous versions of the class and
3912 // during class unloading.
3913 void InstanceKlass::purge_previous_version_list() {
3914   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
3915   assert(has_been_redefined(), "Should only be called for main class");
3916 
3917   // Quick exit.
3918   if (previous_versions() == NULL) {
3919     return;
3920   }
3921 
3922   // This klass has previous versions so see what we can cleanup
3923   // while it is safe to do so.
3924 
3925   int deleted_count = 0;    // leave debugging breadcrumbs
3926   int live_count = 0;
3927   ClassLoaderData* loader_data = class_loader_data();
3928   assert(loader_data != NULL, "should never be null");
3929 
3930   ResourceMark rm;
3931   log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name());
3932 
3933   // previous versions are linked together through the InstanceKlass
3934   InstanceKlass* pv_node = previous_versions();
3935   InstanceKlass* last = this;
3936   int version = 0;
3937 
3938   // check the previous versions list
3939   for (; pv_node != NULL; ) {
3940 
3941     ConstantPool* pvcp = pv_node->constants();
3942     assert(pvcp != NULL, "cp ref was unexpectedly cleared");
3943 
3944     if (!pvcp->on_stack()) {
3945       // If the constant pool isn't on stack, none of the methods
3946       // are executing.  Unlink this previous_version.
3947       // The previous version InstanceKlass is on the ClassLoaderData deallocate list
3948       // so will be deallocated during the next phase of class unloading.
3949       log_trace(redefine, class, iklass, purge)
3950         ("previous version " INTPTR_FORMAT " is dead.", p2i(pv_node));
3951       // For debugging purposes.
3952       pv_node->set_is_scratch_class();
3953       // Unlink from previous version list.
3954       assert(pv_node->class_loader_data() == loader_data, "wrong loader_data");
3955       InstanceKlass* next = pv_node->previous_versions();
3956       pv_node->link_previous_versions(NULL);   // point next to NULL
3957       last->link_previous_versions(next);
3958       // Add to the deallocate list after unlinking
3959       loader_data->add_to_deallocate_list(pv_node);
3960       pv_node = next;
3961       deleted_count++;
3962       version++;
3963       continue;
3964     } else {
3965       log_trace(redefine, class, iklass, purge)("previous version " INTPTR_FORMAT " is alive", p2i(pv_node));
3966       assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
3967       guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
3968       live_count++;
3969       // found a previous version for next time we do class unloading
3970       _has_previous_versions = true;
3971     }
3972 
3973     // At least one method is live in this previous version.
3974     // Reset dead EMCP methods not to get breakpoints.
3975     // All methods are deallocated when all of the methods for this class are no
3976     // longer running.
3977     Array<Method*>* method_refs = pv_node->methods();
3978     if (method_refs != NULL) {
3979       log_trace(redefine, class, iklass, purge)("previous methods length=%d", method_refs->length());
3980       for (int j = 0; j < method_refs->length(); j++) {
3981         Method* method = method_refs->at(j);
3982 
3983         if (!method->on_stack()) {
3984           // no breakpoints for non-running methods
3985           if (method->is_running_emcp()) {
3986             method->set_running_emcp(false);
3987           }
3988         } else {
3989           assert (method->is_obsolete() || method->is_running_emcp(),
3990                   "emcp method cannot run after emcp bit is cleared");
3991           log_trace(redefine, class, iklass, purge)
3992             ("purge: %s(%s): prev method @%d in version @%d is alive",
3993              method->name()->as_C_string(), method->signature()->as_C_string(), j, version);
3994         }
3995       }
3996     }
3997     // next previous version
3998     last = pv_node;
3999     pv_node = pv_node->previous_versions();
4000     version++;
4001   }
4002   log_trace(redefine, class, iklass, purge)
4003     ("previous version stats: live=%d, deleted=%d", live_count, deleted_count);
4004 }
4005 
4006 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,
4007                                                 int emcp_method_count) {
4008   int obsolete_method_count = old_methods->length() - emcp_method_count;
4009 
4010   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
4011       _previous_versions != NULL) {
4012     // We have a mix of obsolete and EMCP methods so we have to
4013     // clear out any matching EMCP method entries the hard way.
4014     int local_count = 0;
4015     for (int i = 0; i < old_methods->length(); i++) {
4016       Method* old_method = old_methods->at(i);
4017       if (old_method->is_obsolete()) {
4018         // only obsolete methods are interesting
4019         Symbol* m_name = old_method->name();
4020         Symbol* m_signature = old_method->signature();
4021 
4022         // previous versions are linked together through the InstanceKlass
4023         int j = 0;
4024         for (InstanceKlass* prev_version = _previous_versions;
4025              prev_version != NULL;
4026              prev_version = prev_version->previous_versions(), j++) {
4027 
4028           Array<Method*>* method_refs = prev_version->methods();
4029           for (int k = 0; k < method_refs->length(); k++) {
4030             Method* method = method_refs->at(k);
4031 
4032             if (!method->is_obsolete() &&
4033                 method->name() == m_name &&
4034                 method->signature() == m_signature) {
4035               // The current RedefineClasses() call has made all EMCP
4036               // versions of this method obsolete so mark it as obsolete
4037               log_trace(redefine, class, iklass, add)
4038                 ("%s(%s): flush obsolete method @%d in version @%d",
4039                  m_name->as_C_string(), m_signature->as_C_string(), k, j);
4040 
4041               method->set_is_obsolete();
4042               break;
4043             }
4044           }
4045 
4046           // The previous loop may not find a matching EMCP method, but
4047           // that doesn't mean that we can optimize and not go any
4048           // further back in the PreviousVersion generations. The EMCP
4049           // method for this generation could have already been made obsolete,
4050           // but there still may be an older EMCP method that has not
4051           // been made obsolete.
4052         }
4053 
4054         if (++local_count >= obsolete_method_count) {
4055           // no more obsolete methods so bail out now
4056           break;
4057         }
4058       }
4059     }
4060   }
4061 }
4062 
4063 // Save the scratch_class as the previous version if any of the methods are running.
4064 // The previous_versions are used to set breakpoints in EMCP methods and they are
4065 // also used to clean MethodData links to redefined methods that are no longer running.
4066 void InstanceKlass::add_previous_version(InstanceKlass* scratch_class,
4067                                          int emcp_method_count) {
4068   assert(Thread::current()->is_VM_thread(),
4069          "only VMThread can add previous versions");
4070 
4071   ResourceMark rm;
4072   log_trace(redefine, class, iklass, add)
4073     ("adding previous version ref for %s, EMCP_cnt=%d", scratch_class->external_name(), emcp_method_count);
4074 
4075   // Clean out old previous versions for this class
4076   purge_previous_version_list();
4077 
4078   // Mark newly obsolete methods in remaining previous versions.  An EMCP method from
4079   // a previous redefinition may be made obsolete by this redefinition.
4080   Array<Method*>* old_methods = scratch_class->methods();
4081   mark_newly_obsolete_methods(old_methods, emcp_method_count);
4082 
4083   // If the constant pool for this previous version of the class
4084   // is not marked as being on the stack, then none of the methods
4085   // in this previous version of the class are on the stack so
4086   // we don't need to add this as a previous version.
4087   ConstantPool* cp_ref = scratch_class->constants();
4088   if (!cp_ref->on_stack()) {
4089     log_trace(redefine, class, iklass, add)("scratch class not added; no methods are running");
4090     // For debugging purposes.
4091     scratch_class->set_is_scratch_class();
4092     scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class);
4093     return;
4094   }
4095 
4096   if (emcp_method_count != 0) {
4097     // At least one method is still running, check for EMCP methods
4098     for (int i = 0; i < old_methods->length(); i++) {
4099       Method* old_method = old_methods->at(i);
4100       if (!old_method->is_obsolete() && old_method->on_stack()) {
4101         // if EMCP method (not obsolete) is on the stack, mark as EMCP so that
4102         // we can add breakpoints for it.
4103 
4104         // We set the method->on_stack bit during safepoints for class redefinition
4105         // and use this bit to set the is_running_emcp bit.
4106         // After the safepoint, the on_stack bit is cleared and the running emcp
4107         // method may exit.   If so, we would set a breakpoint in a method that
4108         // is never reached, but this won't be noticeable to the programmer.
4109         old_method->set_running_emcp(true);
4110         log_trace(redefine, class, iklass, add)
4111           ("EMCP method %s is on_stack " INTPTR_FORMAT, old_method->name_and_sig_as_C_string(), p2i(old_method));
4112       } else if (!old_method->is_obsolete()) {
4113         log_trace(redefine, class, iklass, add)
4114           ("EMCP method %s is NOT on_stack " INTPTR_FORMAT, old_method->name_and_sig_as_C_string(), p2i(old_method));
4115       }
4116     }
4117   }
4118 
4119   // Add previous version if any methods are still running.
4120   // Set has_previous_version flag for processing during class unloading.
4121   _has_previous_versions = true;
4122   log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack.");
4123   assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");
4124   scratch_class->link_previous_versions(previous_versions());
4125   link_previous_versions(scratch_class);
4126 } // end add_previous_version()
4127 
4128 #endif // INCLUDE_JVMTI
4129 
4130 Method* InstanceKlass::method_with_idnum(int idnum) {
4131   Method* m = NULL;
4132   if (idnum < methods()->length()) {
4133     m = methods()->at(idnum);
4134   }
4135   if (m == NULL || m->method_idnum() != idnum) {
4136     for (int index = 0; index < methods()->length(); ++index) {
4137       m = methods()->at(index);
4138       if (m->method_idnum() == idnum) {
4139         return m;
4140       }
4141     }
4142     // None found, return null for the caller to handle.
4143     return NULL;
4144   }
4145   return m;
4146 }
4147 
4148 
4149 Method* InstanceKlass::method_with_orig_idnum(int idnum) {
4150   if (idnum >= methods()->length()) {
4151     return NULL;
4152   }
4153   Method* m = methods()->at(idnum);
4154   if (m != NULL && m->orig_method_idnum() == idnum) {
4155     return m;
4156   }
4157   // Obsolete method idnum does not match the original idnum
4158   for (int index = 0; index < methods()->length(); ++index) {
4159     m = methods()->at(index);
4160     if (m->orig_method_idnum() == idnum) {
4161       return m;
4162     }
4163   }
4164   // None found, return null for the caller to handle.
4165   return NULL;
4166 }
4167 
4168 
4169 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {
4170   InstanceKlass* holder = get_klass_version(version);
4171   if (holder == NULL) {
4172     return NULL; // The version of klass is gone, no method is found
4173   }
4174   Method* method = holder->method_with_orig_idnum(idnum);
4175   return method;
4176 }
4177 
4178 #if INCLUDE_JVMTI
4179 JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() {
4180   return _cached_class_file;
4181 }
4182 
4183 jint InstanceKlass::get_cached_class_file_len() {
4184   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
4185 }
4186 
4187 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
4188   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
4189 }
4190 #endif
4191 
4192 #define THROW_DVT_ERROR(s) \
4193   Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_IncompatibleClassChangeError(), \
4194       "ValueCapableClass class '%s' %s", external_name(),(s)); \
4195       return