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