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