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