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