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