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