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