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