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