1 /*
   2  * Copyright (c) 1997, 2014, 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_implementation/shared/markSweep.inline.hpp"
  32 #include "gc_interface/collectedHeap.inline.hpp"
  33 #include "interpreter/oopMapCache.hpp"
  34 #include "interpreter/rewriter.hpp"
  35 #include "jvmtifiles/jvmti.h"
  36 #include "memory/genOopClosures.inline.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.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/jvmtiRedefineClassesTrace.hpp"
  52 #include "prims/jvmtiRedefineClasses.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 #if INCLUDE_ALL_GCS
  67 #include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
  68 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
  69 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
  70 #include "gc_implementation/g1/g1RemSet.inline.hpp"
  71 #include "gc_implementation/g1/heapRegionManager.inline.hpp"
  72 #include "gc_implementation/parNew/parOopClosures.inline.hpp"
  73 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp"
  74 #include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
  75 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
  76 #include "oops/oop.pcgc.inline.hpp"
  77 #endif // INCLUDE_ALL_GCS
  78 #ifdef COMPILER1
  79 #include "c1/c1_Compiler.hpp"
  80 #endif
  81 
  82 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  83 
  84 #ifdef DTRACE_ENABLED
  85 
  86 
  87 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
  88 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
  89 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
  90 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
  91 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
  92 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
  93 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
  94 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
  95 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
  96   {                                                              \
  97     char* data = NULL;                                           \
  98     int len = 0;                                                 \
  99     Symbol* name = (clss)->name();                               \
 100     if (name != NULL) {                                          \
 101       data = (char*)name->bytes();                               \
 102       len = name->utf8_length();                                 \
 103     }                                                            \
 104     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
 105       data, len, (clss)->class_loader(), thread_type);           \
 106   }
 107 
 108 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
 109   {                                                              \
 110     char* data = NULL;                                           \
 111     int len = 0;                                                 \
 112     Symbol* name = (clss)->name();                               \
 113     if (name != NULL) {                                          \
 114       data = (char*)name->bytes();                               \
 115       len = name->utf8_length();                                 \
 116     }                                                            \
 117     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
 118       data, len, (clss)->class_loader(), thread_type, wait);     \
 119   }
 120 
 121 #else //  ndef DTRACE_ENABLED
 122 
 123 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)
 124 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait)
 125 
 126 #endif //  ndef DTRACE_ENABLED
 127 
 128 volatile int InstanceKlass::_total_instanceKlass_count = 0;
 129 
 130 InstanceKlass* InstanceKlass::allocate_instance_klass(
 131                                               ClassLoaderData* loader_data,
 132                                               int vtable_len,
 133                                               int itable_len,
 134                                               int static_field_size,
 135                                               int nonstatic_oop_map_size,
 136                                               ReferenceType rt,
 137                                               AccessFlags access_flags,
 138                                               Symbol* name,
 139                                               Klass* super_klass,
 140                                               bool is_anonymous,
 141                                               TRAPS) {
 142 
 143   int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
 144                                  access_flags.is_interface(), is_anonymous);
 145 
 146   // Allocation
 147   InstanceKlass* ik;
 148   if (rt == REF_NONE) {
 149     if (name == vmSymbols::java_lang_Class()) {
 150       ik = new (loader_data, size, THREAD) InstanceMirrorKlass(
 151         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
 152         access_flags, is_anonymous);
 153     } else if (name == vmSymbols::java_lang_ClassLoader() ||
 154           (SystemDictionary::ClassLoader_klass_loaded() &&
 155           super_klass != NULL &&
 156           super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {
 157       ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(
 158         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
 159         access_flags, is_anonymous);
 160     } else {
 161       // normal class
 162       ik = new (loader_data, size, THREAD) InstanceKlass(
 163         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
 164         access_flags, is_anonymous);
 165     }
 166   } else {
 167     // reference klass
 168     ik = new (loader_data, size, THREAD) InstanceRefKlass(
 169         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
 170         access_flags, is_anonymous);
 171   }
 172 
 173   // Check for pending exception before adding to the loader data and incrementing
 174   // class count.  Can get OOM here.
 175   if (HAS_PENDING_EXCEPTION) {
 176     return NULL;
 177   }
 178 
 179   // Add all classes to our internal class loader list here,
 180   // including classes in the bootstrap (NULL) class loader.
 181   loader_data->add_class(ik);
 182 
 183   Atomic::inc(&_total_instanceKlass_count);
 184   return ik;
 185 }
 186 
 187 
 188 // copy method ordering from resource area to Metaspace
 189 void InstanceKlass::copy_method_ordering(intArray* m, TRAPS) {
 190   if (m != NULL) {
 191     // allocate a new array and copy contents (memcpy?)
 192     _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
 193     for (int i = 0; i < m->length(); i++) {
 194       _method_ordering->at_put(i, m->at(i));
 195     }
 196   } else {
 197     _method_ordering = Universe::the_empty_int_array();
 198   }
 199 }
 200 
 201 // create a new array of vtable_indices for default methods
 202 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
 203   Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
 204   assert(default_vtable_indices() == NULL, "only create once");
 205   set_default_vtable_indices(vtable_indices);
 206   return vtable_indices;
 207 }
 208 
 209 InstanceKlass::InstanceKlass(int vtable_len,
 210                              int itable_len,
 211                              int static_field_size,
 212                              int nonstatic_oop_map_size,
 213                              ReferenceType rt,
 214                              AccessFlags access_flags,
 215                              bool is_anonymous) {
 216   No_Safepoint_Verifier no_safepoint; // until k becomes parsable
 217 
 218   int iksize = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
 219                                    access_flags.is_interface(), is_anonymous);
 220 
 221   set_vtable_length(vtable_len);
 222   set_itable_length(itable_len);
 223   set_static_field_size(static_field_size);
 224   set_nonstatic_oop_map_size(nonstatic_oop_map_size);
 225   set_access_flags(access_flags);
 226   _misc_flags = 0;  // initialize to zero
 227   set_is_anonymous(is_anonymous);
 228   assert(size() == iksize, "wrong size for object");
 229 
 230   set_array_klasses(NULL);
 231   set_methods(NULL);
 232   set_method_ordering(NULL);
 233   set_default_methods(NULL);
 234   set_default_vtable_indices(NULL);
 235   set_local_interfaces(NULL);
 236   set_transitive_interfaces(NULL);
 237   init_implementor();
 238   set_fields(NULL, 0);
 239   set_constants(NULL);
 240   set_class_loader_data(NULL);
 241   set_source_file_name_index(0);
 242   set_source_debug_extension(NULL, 0);
 243   set_array_name(NULL);
 244   set_inner_classes(NULL);
 245   set_static_oop_field_count(0);
 246   set_nonstatic_field_size(0);
 247   set_is_marked_dependent(false);
 248   set_has_unloaded_dependent(false);
 249   set_init_state(InstanceKlass::allocated);
 250   set_init_thread(NULL);
 251   set_reference_type(rt);
 252   set_oop_map_cache(NULL);
 253   set_jni_ids(NULL);
 254   set_osr_nmethods_head(NULL);
 255   set_breakpoints(NULL);
 256   init_previous_versions();
 257   set_generic_signature_index(0);
 258   release_set_methods_jmethod_ids(NULL);
 259   set_annotations(NULL);
 260   set_jvmti_cached_class_field_map(NULL);
 261   set_initial_method_idnum(0);
 262   _dependencies = NULL;
 263   set_jvmti_cached_class_field_map(NULL);
 264   set_cached_class_file(NULL);
 265   set_initial_method_idnum(0);
 266   set_minor_version(0);
 267   set_major_version(0);
 268   NOT_PRODUCT(_verify_count = 0;)
 269 
 270   // initialize the non-header words to zero
 271   intptr_t* p = (intptr_t*)this;
 272   for (int index = InstanceKlass::header_size(); index < iksize; index++) {
 273     p[index] = NULL_WORD;
 274   }
 275 
 276   // Set temporary value until parseClassFile updates it with the real instance
 277   // size.
 278   set_layout_helper(Klass::instance_layout_helper(0, true));
 279 }
 280 
 281 
 282 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
 283                                        Array<Method*>* methods) {
 284   if (methods != NULL && methods != Universe::the_empty_method_array() &&
 285       !methods->is_shared()) {
 286     for (int i = 0; i < methods->length(); i++) {
 287       Method* method = methods->at(i);
 288       if (method == NULL) continue;  // maybe null if error processing
 289       // Only want to delete methods that are not executing for RedefineClasses.
 290       // The previous version will point to them so they're not totally dangling
 291       assert (!method->on_stack(), "shouldn't be called with methods on stack");
 292       MetadataFactory::free_metadata(loader_data, method);
 293     }
 294     MetadataFactory::free_array<Method*>(loader_data, methods);
 295   }
 296 }
 297 
 298 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
 299                                           Klass* super_klass,
 300                                           Array<Klass*>* local_interfaces,
 301                                           Array<Klass*>* transitive_interfaces) {
 302   // Only deallocate transitive interfaces if not empty, same as super class
 303   // or same as local interfaces.  See code in parseClassFile.
 304   Array<Klass*>* ti = transitive_interfaces;
 305   if (ti != Universe::the_empty_klass_array() && ti != local_interfaces) {
 306     // check that the interfaces don't come from super class
 307     Array<Klass*>* sti = (super_klass == NULL) ? NULL :
 308                     InstanceKlass::cast(super_klass)->transitive_interfaces();
 309     if (ti != sti && ti != NULL && !ti->is_shared()) {
 310       MetadataFactory::free_array<Klass*>(loader_data, ti);
 311     }
 312   }
 313 
 314   // local interfaces can be empty
 315   if (local_interfaces != Universe::the_empty_klass_array() &&
 316       local_interfaces != NULL && !local_interfaces->is_shared()) {
 317     MetadataFactory::free_array<Klass*>(loader_data, local_interfaces);
 318   }
 319 }
 320 
 321 // This function deallocates the metadata and C heap pointers that the
 322 // InstanceKlass points to.
 323 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
 324 
 325   // Orphan the mirror first, CMS thinks it's still live.
 326   if (java_mirror() != NULL) {
 327     java_lang_Class::set_klass(java_mirror(), NULL);
 328   }
 329 
 330   // Need to take this class off the class loader data list.
 331   loader_data->remove_class(this);
 332 
 333   // The array_klass for this class is created later, after error handling.
 334   // For class redefinition, we keep the original class so this scratch class
 335   // doesn't have an array class.  Either way, assert that there is nothing
 336   // to deallocate.
 337   assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
 338 
 339   // Release C heap allocated data that this might point to, which includes
 340   // reference counting symbol names.
 341   release_C_heap_structures();
 342 
 343   deallocate_methods(loader_data, methods());
 344   set_methods(NULL);
 345 
 346   if (method_ordering() != NULL &&
 347       method_ordering() != Universe::the_empty_int_array() &&
 348       !method_ordering()->is_shared()) {
 349     MetadataFactory::free_array<int>(loader_data, method_ordering());
 350   }
 351   set_method_ordering(NULL);
 352 
 353   // default methods can be empty
 354   if (default_methods() != NULL &&
 355       default_methods() != Universe::the_empty_method_array() &&
 356       !default_methods()->is_shared()) {
 357     MetadataFactory::free_array<Method*>(loader_data, default_methods());
 358   }
 359   // Do NOT deallocate the default methods, they are owned by superinterfaces.
 360   set_default_methods(NULL);
 361 
 362   // default methods vtable indices can be empty
 363   if (default_vtable_indices() != NULL &&
 364       !default_vtable_indices()->is_shared()) {
 365     MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
 366   }
 367   set_default_vtable_indices(NULL);
 368 
 369 
 370   // This array is in Klass, but remove it with the InstanceKlass since
 371   // this place would be the only caller and it can share memory with transitive
 372   // interfaces.
 373   if (secondary_supers() != NULL &&
 374       secondary_supers() != Universe::the_empty_klass_array() &&
 375       secondary_supers() != transitive_interfaces() &&
 376       !secondary_supers()->is_shared()) {
 377     MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
 378   }
 379   set_secondary_supers(NULL);
 380 
 381   deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
 382   set_transitive_interfaces(NULL);
 383   set_local_interfaces(NULL);
 384 
 385   if (fields() != NULL && !fields()->is_shared()) {
 386     MetadataFactory::free_array<jushort>(loader_data, fields());
 387   }
 388   set_fields(NULL, 0);
 389 
 390   // If a method from a redefined class is using this constant pool, don't
 391   // delete it, yet.  The new class's previous version will point to this.
 392   if (constants() != NULL) {
 393     assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
 394     if (!constants()->is_shared()) {
 395       MetadataFactory::free_metadata(loader_data, constants());
 396     }
 397     set_constants(NULL);
 398   }
 399 
 400   if (inner_classes() != NULL &&
 401       inner_classes() != Universe::the_empty_short_array() &&
 402       !inner_classes()->is_shared()) {
 403     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
 404   }
 405   set_inner_classes(NULL);
 406 
 407   // We should deallocate the Annotations instance if it's not in shared spaces.
 408   if (annotations() != NULL && !annotations()->is_shared()) {
 409     MetadataFactory::free_metadata(loader_data, annotations());
 410   }
 411   set_annotations(NULL);
 412 }
 413 
 414 bool InstanceKlass::should_be_initialized() const {
 415   return !is_initialized();
 416 }
 417 
 418 klassVtable* InstanceKlass::vtable() const {
 419   return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());
 420 }
 421 
 422 klassItable* InstanceKlass::itable() const {
 423   return new klassItable(instanceKlassHandle(this));
 424 }
 425 
 426 void InstanceKlass::eager_initialize(Thread *thread) {
 427   if (!EagerInitialization) return;
 428 
 429   if (this->is_not_initialized()) {
 430     // abort if the the class has a class initializer
 431     if (this->class_initializer() != NULL) return;
 432 
 433     // abort if it is java.lang.Object (initialization is handled in genesis)
 434     Klass* super = this->super();
 435     if (super == NULL) return;
 436 
 437     // abort if the super class should be initialized
 438     if (!InstanceKlass::cast(super)->is_initialized()) return;
 439 
 440     // call body to expose the this pointer
 441     instanceKlassHandle this_k(thread, this);
 442     eager_initialize_impl(this_k);
 443   }
 444 }
 445 
 446 // JVMTI spec thinks there are signers and protection domain in the
 447 // instanceKlass.  These accessors pretend these fields are there.
 448 // The hprof specification also thinks these fields are in InstanceKlass.
 449 oop InstanceKlass::protection_domain() const {
 450   // return the protection_domain from the mirror
 451   return java_lang_Class::protection_domain(java_mirror());
 452 }
 453 
 454 // To remove these from requires an incompatible change and CCC request.
 455 objArrayOop InstanceKlass::signers() const {
 456   // return the signers from the mirror
 457   return java_lang_Class::signers(java_mirror());
 458 }
 459 
 460 oop InstanceKlass::init_lock() const {
 461   // return the init lock from the mirror
 462   oop lock = java_lang_Class::init_lock(java_mirror());
 463   // Prevent reordering with any access of initialization state
 464   OrderAccess::loadload();
 465   assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state
 466          "only fully initialized state can have a null lock");
 467   return lock;
 468 }
 469 
 470 // Set the initialization lock to null so the object can be GC'ed.  Any racing
 471 // threads to get this lock will see a null lock and will not lock.
 472 // That's okay because they all check for initialized state after getting
 473 // the lock and return.
 474 void InstanceKlass::fence_and_clear_init_lock() {
 475   // make sure previous stores are all done, notably the init_state.
 476   OrderAccess::storestore();
 477   java_lang_Class::set_init_lock(java_mirror(), NULL);
 478   assert(!is_not_initialized(), "class must be initialized now");
 479 }
 480 
 481 void InstanceKlass::eager_initialize_impl(instanceKlassHandle this_k) {
 482   EXCEPTION_MARK;
 483   oop init_lock = this_k->init_lock();
 484   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
 485 
 486   // abort if someone beat us to the initialization
 487   if (!this_k->is_not_initialized()) return;  // note: not equivalent to is_initialized()
 488 
 489   ClassState old_state = this_k->init_state();
 490   link_class_impl(this_k, true, THREAD);
 491   if (HAS_PENDING_EXCEPTION) {
 492     CLEAR_PENDING_EXCEPTION;
 493     // Abort if linking the class throws an exception.
 494 
 495     // Use a test to avoid redundantly resetting the state if there's
 496     // no change.  Set_init_state() asserts that state changes make
 497     // progress, whereas here we might just be spinning in place.
 498     if( old_state != this_k->_init_state )
 499       this_k->set_init_state (old_state);
 500   } else {
 501     // linking successfull, mark class as initialized
 502     this_k->set_init_state (fully_initialized);
 503     this_k->fence_and_clear_init_lock();
 504     // trace
 505     if (TraceClassInitialization) {
 506       ResourceMark rm(THREAD);
 507       tty->print_cr("[Initialized %s without side effects]", this_k->external_name());
 508     }
 509   }
 510 }
 511 
 512 
 513 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
 514 // process. The step comments refers to the procedure described in that section.
 515 // Note: implementation moved to static method to expose the this pointer.
 516 void InstanceKlass::initialize(TRAPS) {
 517   if (this->should_be_initialized()) {
 518     HandleMark hm(THREAD);
 519     instanceKlassHandle this_k(THREAD, this);
 520     initialize_impl(this_k, CHECK);
 521     // Note: at this point the class may be initialized
 522     //       OR it may be in the state of being initialized
 523     //       in case of recursive initialization!
 524   } else {
 525     assert(is_initialized(), "sanity check");
 526   }
 527 }
 528 
 529 
 530 bool InstanceKlass::verify_code(
 531     instanceKlassHandle this_k, bool throw_verifyerror, TRAPS) {
 532   // 1) Verify the bytecodes
 533   Verifier::Mode mode =
 534     throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
 535   return Verifier::verify(this_k, mode, this_k->should_verify_class(), CHECK_false);
 536 }
 537 
 538 
 539 // Used exclusively by the shared spaces dump mechanism to prevent
 540 // classes mapped into the shared regions in new VMs from appearing linked.
 541 
 542 void InstanceKlass::unlink_class() {
 543   assert(is_linked(), "must be linked");
 544   _init_state = loaded;
 545 }
 546 
 547 void InstanceKlass::link_class(TRAPS) {
 548   assert(is_loaded(), "must be loaded");
 549   if (!is_linked()) {
 550     HandleMark hm(THREAD);
 551     instanceKlassHandle this_k(THREAD, this);
 552     link_class_impl(this_k, true, CHECK);
 553   }
 554 }
 555 
 556 // Called to verify that a class can link during initialization, without
 557 // throwing a VerifyError.
 558 bool InstanceKlass::link_class_or_fail(TRAPS) {
 559   assert(is_loaded(), "must be loaded");
 560   if (!is_linked()) {
 561     HandleMark hm(THREAD);
 562     instanceKlassHandle this_k(THREAD, this);
 563     link_class_impl(this_k, false, CHECK_false);
 564   }
 565   return is_linked();
 566 }
 567 
 568 bool InstanceKlass::link_class_impl(
 569     instanceKlassHandle this_k, bool throw_verifyerror, TRAPS) {
 570   // check for error state
 571   if (this_k->is_in_error_state()) {
 572     ResourceMark rm(THREAD);
 573     THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
 574                this_k->external_name(), false);
 575   }
 576   // return if already verified
 577   if (this_k->is_linked()) {
 578     return true;
 579   }
 580 
 581   // Timing
 582   // timer handles recursion
 583   assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
 584   JavaThread* jt = (JavaThread*)THREAD;
 585 
 586   // link super class before linking this class
 587   instanceKlassHandle super(THREAD, this_k->super());
 588   if (super.not_null()) {
 589     if (super->is_interface()) {  // check if super class is an interface
 590       ResourceMark rm(THREAD);
 591       Exceptions::fthrow(
 592         THREAD_AND_LOCATION,
 593         vmSymbols::java_lang_IncompatibleClassChangeError(),
 594         "class %s has interface %s as super class",
 595         this_k->external_name(),
 596         super->external_name()
 597       );
 598       return false;
 599     }
 600 
 601     link_class_impl(super, throw_verifyerror, CHECK_false);
 602   }
 603 
 604   // link all interfaces implemented by this class before linking this class
 605   Array<Klass*>* interfaces = this_k->local_interfaces();
 606   int num_interfaces = interfaces->length();
 607   for (int index = 0; index < num_interfaces; index++) {
 608     HandleMark hm(THREAD);
 609     instanceKlassHandle ih(THREAD, interfaces->at(index));
 610     link_class_impl(ih, throw_verifyerror, CHECK_false);
 611   }
 612 
 613   // in case the class is linked in the process of linking its superclasses
 614   if (this_k->is_linked()) {
 615     return true;
 616   }
 617 
 618   // trace only the link time for this klass that includes
 619   // the verification time
 620   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
 621                              ClassLoader::perf_class_link_selftime(),
 622                              ClassLoader::perf_classes_linked(),
 623                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 624                              jt->get_thread_stat()->perf_timers_addr(),
 625                              PerfClassTraceTime::CLASS_LINK);
 626 
 627   // verification & rewriting
 628   {
 629     oop init_lock = this_k->init_lock();
 630     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
 631     // rewritten will have been set if loader constraint error found
 632     // on an earlier link attempt
 633     // don't verify or rewrite if already rewritten
 634 
 635     if (!this_k->is_linked()) {
 636       if (!this_k->is_rewritten()) {
 637         {
 638           // Timer includes any side effects of class verification (resolution,
 639           // etc), but not recursive entry into verify_code().
 640           PerfClassTraceTime timer(ClassLoader::perf_class_verify_time(),
 641                                    ClassLoader::perf_class_verify_selftime(),
 642                                    ClassLoader::perf_classes_verified(),
 643                                    jt->get_thread_stat()->perf_recursion_counts_addr(),
 644                                    jt->get_thread_stat()->perf_timers_addr(),
 645                                    PerfClassTraceTime::CLASS_VERIFY);
 646           bool verify_ok = verify_code(this_k, throw_verifyerror, THREAD);
 647           if (!verify_ok) {
 648             return false;
 649           }
 650         }
 651 
 652         // Just in case a side-effect of verify linked this class already
 653         // (which can sometimes happen since the verifier loads classes
 654         // using custom class loaders, which are free to initialize things)
 655         if (this_k->is_linked()) {
 656           return true;
 657         }
 658 
 659         // also sets rewritten
 660         this_k->rewrite_class(CHECK_false);
 661       }
 662 
 663       // relocate jsrs and link methods after they are all rewritten
 664       this_k->link_methods(CHECK_false);
 665 
 666       // Initialize the vtable and interface table after
 667       // methods have been rewritten since rewrite may
 668       // fabricate new Method*s.
 669       // also does loader constraint checking
 670       if (!this_k()->is_shared()) {
 671         ResourceMark rm(THREAD);
 672         this_k->vtable()->initialize_vtable(true, CHECK_false);
 673         this_k->itable()->initialize_itable(true, CHECK_false);
 674       }
 675 #ifdef ASSERT
 676       else {
 677         ResourceMark rm(THREAD);
 678         this_k->vtable()->verify(tty, true);
 679         // In case itable verification is ever added.
 680         // this_k->itable()->verify(tty, true);
 681       }
 682 #endif
 683       this_k->set_init_state(linked);
 684       if (JvmtiExport::should_post_class_prepare()) {
 685         Thread *thread = THREAD;
 686         assert(thread->is_Java_thread(), "thread->is_Java_thread()");
 687         JvmtiExport::post_class_prepare((JavaThread *) thread, this_k());
 688       }
 689     }
 690   }
 691   return true;
 692 }
 693 
 694 
 695 // Rewrite the byte codes of all of the methods of a class.
 696 // The rewriter must be called exactly once. Rewriting must happen after
 697 // verification but before the first method of the class is executed.
 698 void InstanceKlass::rewrite_class(TRAPS) {
 699   assert(is_loaded(), "must be loaded");
 700   instanceKlassHandle this_k(THREAD, this);
 701   if (this_k->is_rewritten()) {
 702     assert(this_k()->is_shared(), "rewriting an unshared class?");
 703     return;
 704   }
 705   Rewriter::rewrite(this_k, CHECK);
 706   this_k->set_rewritten();
 707 }
 708 
 709 // Now relocate and link method entry points after class is rewritten.
 710 // This is outside is_rewritten flag. In case of an exception, it can be
 711 // executed more than once.
 712 void InstanceKlass::link_methods(TRAPS) {
 713   int len = methods()->length();
 714   for (int i = len-1; i >= 0; i--) {
 715     methodHandle m(THREAD, methods()->at(i));
 716 
 717     // Set up method entry points for compiler and interpreter    .
 718     m->link_method(m, CHECK);
 719 
 720     // This is for JVMTI and unrelated to relocator but the last thing we do
 721 #ifdef ASSERT
 722     if (StressMethodComparator) {
 723       ResourceMark rm(THREAD);
 724       static int nmc = 0;
 725       for (int j = i; j >= 0 && j >= i-4; j--) {
 726         if ((++nmc % 1000) == 0)  tty->print_cr("Have run MethodComparator %d times...", nmc);
 727         bool z = MethodComparator::methods_EMCP(m(),
 728                    methods()->at(j));
 729         if (j == i && !z) {
 730           tty->print("MethodComparator FAIL: "); m->print(); m->print_codes();
 731           assert(z, "method must compare equal to itself");
 732         }
 733       }
 734     }
 735 #endif //ASSERT
 736   }
 737 }
 738 
 739 
 740 void InstanceKlass::initialize_impl(instanceKlassHandle this_k, TRAPS) {
 741   // Make sure klass is linked (verified) before initialization
 742   // A class could already be verified, since it has been reflected upon.
 743   this_k->link_class(CHECK);
 744 
 745   DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_k()), -1);
 746 
 747   bool wait = false;
 748 
 749   // refer to the JVM book page 47 for description of steps
 750   // Step 1
 751   {
 752     oop init_lock = this_k->init_lock();
 753     ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
 754 
 755     Thread *self = THREAD; // it's passed the current thread
 756 
 757     // Step 2
 758     // If we were to use wait() instead of waitInterruptibly() then
 759     // we might end up throwing IE from link/symbol resolution sites
 760     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
 761     while(this_k->is_being_initialized() && !this_k->is_reentrant_initialization(self)) {
 762         wait = true;
 763       ol.waitUninterruptibly(CHECK);
 764     }
 765 
 766     // Step 3
 767     if (this_k->is_being_initialized() && this_k->is_reentrant_initialization(self)) {
 768       DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_k()), -1,wait);
 769       return;
 770     }
 771 
 772     // Step 4
 773     if (this_k->is_initialized()) {
 774       DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_k()), -1,wait);
 775       return;
 776     }
 777 
 778     // Step 5
 779     if (this_k->is_in_error_state()) {
 780       DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_k()), -1,wait);
 781       ResourceMark rm(THREAD);
 782       const char* desc = "Could not initialize class ";
 783       const char* className = this_k->external_name();
 784       size_t msglen = strlen(desc) + strlen(className) + 1;
 785       char* message = NEW_RESOURCE_ARRAY(char, msglen);
 786       if (NULL == message) {
 787         // Out of memory: can't create detailed error message
 788         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
 789       } else {
 790         jio_snprintf(message, msglen, "%s%s", desc, className);
 791         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
 792       }
 793     }
 794 
 795     // Step 6
 796     this_k->set_init_state(being_initialized);
 797     this_k->set_init_thread(self);
 798   }
 799 
 800   // Step 7
 801   Klass* super_klass = this_k->super();
 802   if (super_klass != NULL && !this_k->is_interface() && super_klass->should_be_initialized()) {
 803     super_klass->initialize(THREAD);
 804 
 805     if (HAS_PENDING_EXCEPTION) {
 806       Handle e(THREAD, PENDING_EXCEPTION);
 807       CLEAR_PENDING_EXCEPTION;
 808       {
 809         EXCEPTION_MARK;
 810         this_k->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
 811         CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, superclass initialization error is thrown below
 812       }
 813       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_k()), -1,wait);
 814       THROW_OOP(e());
 815     }
 816   }
 817 
 818   if (this_k->has_default_methods()) {
 819     // Step 7.5: initialize any interfaces which have default methods
 820     for (int i = 0; i < this_k->local_interfaces()->length(); ++i) {
 821       Klass* iface = this_k->local_interfaces()->at(i);
 822       InstanceKlass* ik = InstanceKlass::cast(iface);
 823       if (ik->has_default_methods() && ik->should_be_initialized()) {
 824         ik->initialize(THREAD);
 825 
 826         if (HAS_PENDING_EXCEPTION) {
 827           Handle e(THREAD, PENDING_EXCEPTION);
 828           CLEAR_PENDING_EXCEPTION;
 829           {
 830             EXCEPTION_MARK;
 831             // Locks object, set state, and notify all waiting threads
 832             this_k->set_initialization_state_and_notify(
 833                 initialization_error, THREAD);
 834 
 835             // ignore any exception thrown, superclass initialization error is
 836             // thrown below
 837             CLEAR_PENDING_EXCEPTION;
 838           }
 839           DTRACE_CLASSINIT_PROBE_WAIT(
 840               super__failed, InstanceKlass::cast(this_k()), -1, wait);
 841           THROW_OOP(e());
 842         }
 843       }
 844     }
 845   }
 846 
 847   // Step 8
 848   {
 849     assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
 850     JavaThread* jt = (JavaThread*)THREAD;
 851     DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_k()), -1,wait);
 852     // Timer includes any side effects of class initialization (resolution,
 853     // etc), but not recursive entry into call_class_initializer().
 854     PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
 855                              ClassLoader::perf_class_init_selftime(),
 856                              ClassLoader::perf_classes_inited(),
 857                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 858                              jt->get_thread_stat()->perf_timers_addr(),
 859                              PerfClassTraceTime::CLASS_CLINIT);
 860     this_k->call_class_initializer(THREAD);
 861   }
 862 
 863   // Step 9
 864   if (!HAS_PENDING_EXCEPTION) {
 865     this_k->set_initialization_state_and_notify(fully_initialized, CHECK);
 866     { ResourceMark rm(THREAD);
 867       debug_only(this_k->vtable()->verify(tty, true);)
 868     }
 869   }
 870   else {
 871     // Step 10 and 11
 872     Handle e(THREAD, PENDING_EXCEPTION);
 873     CLEAR_PENDING_EXCEPTION;
 874     // JVMTI has already reported the pending exception
 875     // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
 876     JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
 877     {
 878       EXCEPTION_MARK;
 879       this_k->set_initialization_state_and_notify(initialization_error, THREAD);
 880       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
 881       // JVMTI has already reported the pending exception
 882       // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
 883       JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
 884     }
 885     DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_k()), -1,wait);
 886     if (e->is_a(SystemDictionary::Error_klass())) {
 887       THROW_OOP(e());
 888     } else {
 889       JavaCallArguments args(e);
 890       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
 891                 vmSymbols::throwable_void_signature(),
 892                 &args);
 893     }
 894   }
 895   DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_k()), -1,wait);
 896 }
 897 
 898 
 899 // Note: implementation moved to static method to expose the this pointer.
 900 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
 901   instanceKlassHandle kh(THREAD, this);
 902   set_initialization_state_and_notify_impl(kh, state, CHECK);
 903 }
 904 
 905 void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_k, ClassState state, TRAPS) {
 906   oop init_lock = this_k->init_lock();
 907   ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
 908   this_k->set_init_state(state);
 909   this_k->fence_and_clear_init_lock();
 910   ol.notify_all(CHECK);
 911 }
 912 
 913 // The embedded _implementor field can only record one implementor.
 914 // When there are more than one implementors, the _implementor field
 915 // is set to the interface Klass* itself. Following are the possible
 916 // values for the _implementor field:
 917 //   NULL                  - no implementor
 918 //   implementor Klass*    - one implementor
 919 //   self                  - more than one implementor
 920 //
 921 // The _implementor field only exists for interfaces.
 922 void InstanceKlass::add_implementor(Klass* k) {
 923   assert(Compile_lock->owned_by_self(), "");
 924   assert(is_interface(), "not interface");
 925   // Filter out my subinterfaces.
 926   // (Note: Interfaces are never on the subklass list.)
 927   if (InstanceKlass::cast(k)->is_interface()) return;
 928 
 929   // Filter out subclasses whose supers already implement me.
 930   // (Note: CHA must walk subclasses of direct implementors
 931   // in order to locate indirect implementors.)
 932   Klass* sk = InstanceKlass::cast(k)->super();
 933   if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
 934     // We only need to check one immediate superclass, since the
 935     // implements_interface query looks at transitive_interfaces.
 936     // Any supers of the super have the same (or fewer) transitive_interfaces.
 937     return;
 938 
 939   Klass* ik = implementor();
 940   if (ik == NULL) {
 941     set_implementor(k);
 942   } else if (ik != this) {
 943     // There is already an implementor. Use itself as an indicator of
 944     // more than one implementors.
 945     set_implementor(this);
 946   }
 947 
 948   // The implementor also implements the transitive_interfaces
 949   for (int index = 0; index < local_interfaces()->length(); index++) {
 950     InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
 951   }
 952 }
 953 
 954 void InstanceKlass::init_implementor() {
 955   if (is_interface()) {
 956     set_implementor(NULL);
 957   }
 958 }
 959 
 960 
 961 void InstanceKlass::process_interfaces(Thread *thread) {
 962   // link this class into the implementors list of every interface it implements
 963   for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
 964     assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
 965     InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
 966     assert(interf->is_interface(), "expected interface");
 967     interf->add_implementor(this);
 968   }
 969 }
 970 
 971 bool InstanceKlass::can_be_primary_super_slow() const {
 972   if (is_interface())
 973     return false;
 974   else
 975     return Klass::can_be_primary_super_slow();
 976 }
 977 
 978 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {
 979   // The secondaries are the implemented interfaces.
 980   InstanceKlass* ik = InstanceKlass::cast(this);
 981   Array<Klass*>* interfaces = ik->transitive_interfaces();
 982   int num_secondaries = num_extra_slots + interfaces->length();
 983   if (num_secondaries == 0) {
 984     // Must share this for correct bootstrapping!
 985     set_secondary_supers(Universe::the_empty_klass_array());
 986     return NULL;
 987   } else if (num_extra_slots == 0) {
 988     // The secondary super list is exactly the same as the transitive interfaces.
 989     // Redefine classes has to be careful not to delete this!
 990     set_secondary_supers(interfaces);
 991     return NULL;
 992   } else {
 993     // Copy transitive interfaces to a temporary growable array to be constructed
 994     // into the secondary super list with extra slots.
 995     GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
 996     for (int i = 0; i < interfaces->length(); i++) {
 997       secondaries->push(interfaces->at(i));
 998     }
 999     return secondaries;
1000   }
1001 }
1002 
1003 bool InstanceKlass::compute_is_subtype_of(Klass* k) {
1004   if (k->is_interface()) {
1005     return implements_interface(k);
1006   } else {
1007     return Klass::compute_is_subtype_of(k);
1008   }
1009 }
1010 
1011 bool InstanceKlass::implements_interface(Klass* k) const {
1012   if (this == k) return true;
1013   assert(k->is_interface(), "should be an interface class");
1014   for (int i = 0; i < transitive_interfaces()->length(); i++) {
1015     if (transitive_interfaces()->at(i) == k) {
1016       return true;
1017     }
1018   }
1019   return false;
1020 }
1021 
1022 bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
1023   // Verify direct super interface
1024   if (this == k) return true;
1025   assert(k->is_interface(), "should be an interface class");
1026   for (int i = 0; i < local_interfaces()->length(); i++) {
1027     if (local_interfaces()->at(i) == k) {
1028       return true;
1029     }
1030   }
1031   return false;
1032 }
1033 
1034 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
1035   if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
1036   if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
1037     report_java_out_of_memory("Requested array size exceeds VM limit");
1038     JvmtiExport::post_array_size_exhausted();
1039     THROW_OOP_0(Universe::out_of_memory_error_array_size());
1040   }
1041   int size = objArrayOopDesc::object_size(length);
1042   Klass* ak = array_klass(n, CHECK_NULL);
1043   KlassHandle h_ak (THREAD, ak);
1044   objArrayOop o =
1045     (objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);
1046   return o;
1047 }
1048 
1049 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
1050   if (TraceFinalizerRegistration) {
1051     tty->print("Registered ");
1052     i->print_value_on(tty);
1053     tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);
1054   }
1055   instanceHandle h_i(THREAD, i);
1056   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1057   JavaValue result(T_VOID);
1058   JavaCallArguments args(h_i);
1059   methodHandle mh (THREAD, Universe::finalizer_register_method());
1060   JavaCalls::call(&result, mh, &args, CHECK_NULL);
1061   return h_i();
1062 }
1063 
1064 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1065   bool has_finalizer_flag = has_finalizer(); // Query before possible GC
1066   int size = size_helper();  // Query before forming handle.
1067 
1068   KlassHandle h_k(THREAD, this);
1069 
1070   instanceOop i;
1071 
1072   i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);
1073   if (has_finalizer_flag && !RegisterFinalizersAtInit) {
1074     i = register_finalizer(i, CHECK_NULL);
1075   }
1076   return i;
1077 }
1078 
1079 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1080   if (is_interface() || is_abstract()) {
1081     ResourceMark rm(THREAD);
1082     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1083               : vmSymbols::java_lang_InstantiationException(), external_name());
1084   }
1085   if (this == SystemDictionary::Class_klass()) {
1086     ResourceMark rm(THREAD);
1087     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1088               : vmSymbols::java_lang_IllegalAccessException(), external_name());
1089   }
1090 }
1091 
1092 Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
1093   instanceKlassHandle this_k(THREAD, this);
1094   return array_klass_impl(this_k, or_null, n, THREAD);
1095 }
1096 
1097 Klass* InstanceKlass::array_klass_impl(instanceKlassHandle this_k, bool or_null, int n, TRAPS) {
1098   if (this_k->array_klasses() == NULL) {
1099     if (or_null) return NULL;
1100 
1101     ResourceMark rm;
1102     JavaThread *jt = (JavaThread *)THREAD;
1103     {
1104       // Atomic creation of array_klasses
1105       MutexLocker mc(Compile_lock, THREAD);   // for vtables
1106       MutexLocker ma(MultiArray_lock, THREAD);
1107 
1108       // Check if update has already taken place
1109       if (this_k->array_klasses() == NULL) {
1110         Klass*    k = ObjArrayKlass::allocate_objArray_klass(this_k->class_loader_data(), 1, this_k, CHECK_NULL);
1111         this_k->set_array_klasses(k);
1112       }
1113     }
1114   }
1115   // _this will always be set at this point
1116   ObjArrayKlass* oak = (ObjArrayKlass*)this_k->array_klasses();
1117   if (or_null) {
1118     return oak->array_klass_or_null(n);
1119   }
1120   return oak->array_klass(n, CHECK_NULL);
1121 }
1122 
1123 Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
1124   return array_klass_impl(or_null, 1, THREAD);
1125 }
1126 
1127 void InstanceKlass::call_class_initializer(TRAPS) {
1128   instanceKlassHandle ik (THREAD, this);
1129   call_class_initializer_impl(ik, THREAD);
1130 }
1131 
1132 static int call_class_initializer_impl_counter = 0;   // for debugging
1133 
1134 Method* InstanceKlass::class_initializer() {
1135   Method* clinit = find_method(
1136       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1137   if (clinit != NULL && clinit->has_valid_initializer_flags()) {
1138     return clinit;
1139   }
1140   return NULL;
1141 }
1142 
1143 void InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_k, TRAPS) {
1144   if (ReplayCompiles &&
1145       (ReplaySuppressInitializers == 1 ||
1146        ReplaySuppressInitializers >= 2 && this_k->class_loader() != NULL)) {
1147     // Hide the existence of the initializer for the purpose of replaying the compile
1148     return;
1149   }
1150 
1151   methodHandle h_method(THREAD, this_k->class_initializer());
1152   assert(!this_k->is_initialized(), "we cannot initialize twice");
1153   if (TraceClassInitialization) {
1154     tty->print("%d Initializing ", call_class_initializer_impl_counter++);
1155     this_k->name()->print_value();
1156     tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", (address)this_k());
1157   }
1158   if (h_method() != NULL) {
1159     JavaCallArguments args; // No arguments
1160     JavaValue result(T_VOID);
1161     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1162   }
1163 }
1164 
1165 
1166 void InstanceKlass::mask_for(methodHandle method, int bci,
1167   InterpreterOopMap* entry_for) {
1168   // Dirty read, then double-check under a lock.
1169   if (_oop_map_cache == NULL) {
1170     // Otherwise, allocate a new one.
1171     MutexLocker x(OopMapCacheAlloc_lock);
1172     // First time use. Allocate a cache in C heap
1173     if (_oop_map_cache == NULL) {
1174       // Release stores from OopMapCache constructor before assignment
1175       // to _oop_map_cache. C++ compilers on ppc do not emit the
1176       // required memory barrier only because of the volatile
1177       // qualifier of _oop_map_cache.
1178       OrderAccess::release_store_ptr(&_oop_map_cache, new OopMapCache());
1179     }
1180   }
1181   // _oop_map_cache is constant after init; lookup below does is own locking.
1182   _oop_map_cache->lookup(method, bci, entry_for);
1183 }
1184 
1185 
1186 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1187   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1188     Symbol* f_name = fs.name();
1189     Symbol* f_sig  = fs.signature();
1190     if (f_name == name && f_sig == sig) {
1191       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1192       return true;
1193     }
1194   }
1195   return false;
1196 }
1197 
1198 
1199 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1200   const int n = local_interfaces()->length();
1201   for (int i = 0; i < n; i++) {
1202     Klass* intf1 = local_interfaces()->at(i);
1203     assert(intf1->is_interface(), "just checking type");
1204     // search for field in current interface
1205     if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
1206       assert(fd->is_static(), "interface field must be static");
1207       return intf1;
1208     }
1209     // search for field in direct superinterfaces
1210     Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
1211     if (intf2 != NULL) return intf2;
1212   }
1213   // otherwise field lookup fails
1214   return NULL;
1215 }
1216 
1217 
1218 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1219   // search order according to newest JVM spec (5.4.3.2, p.167).
1220   // 1) search for field in current klass
1221   if (find_local_field(name, sig, fd)) {
1222     return const_cast<InstanceKlass*>(this);
1223   }
1224   // 2) search for field recursively in direct superinterfaces
1225   { Klass* intf = find_interface_field(name, sig, fd);
1226     if (intf != NULL) return intf;
1227   }
1228   // 3) apply field lookup recursively if superclass exists
1229   { Klass* supr = super();
1230     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
1231   }
1232   // 4) otherwise field lookup fails
1233   return NULL;
1234 }
1235 
1236 
1237 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1238   // search order according to newest JVM spec (5.4.3.2, p.167).
1239   // 1) search for field in current klass
1240   if (find_local_field(name, sig, fd)) {
1241     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1242   }
1243   // 2) search for field recursively in direct superinterfaces
1244   if (is_static) {
1245     Klass* intf = find_interface_field(name, sig, fd);
1246     if (intf != NULL) return intf;
1247   }
1248   // 3) apply field lookup recursively if superclass exists
1249   { Klass* supr = super();
1250     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
1251   }
1252   // 4) otherwise field lookup fails
1253   return NULL;
1254 }
1255 
1256 
1257 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1258   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1259     if (fs.offset() == offset) {
1260       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1261       if (fd->is_static() == is_static) return true;
1262     }
1263   }
1264   return false;
1265 }
1266 
1267 
1268 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1269   Klass* klass = const_cast<InstanceKlass*>(this);
1270   while (klass != NULL) {
1271     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
1272       return true;
1273     }
1274     klass = klass->super();
1275   }
1276   return false;
1277 }
1278 
1279 
1280 void InstanceKlass::methods_do(void f(Method* method)) {
1281   // Methods aren't stable until they are loaded.  This can be read outside
1282   // a lock through the ClassLoaderData for profiling
1283   if (!is_loaded()) {
1284     return;
1285   }
1286 
1287   int len = methods()->length();
1288   for (int index = 0; index < len; index++) {
1289     Method* m = methods()->at(index);
1290     assert(m->is_method(), "must be method");
1291     f(m);
1292   }
1293 }
1294 
1295 
1296 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
1297   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1298     if (fs.access_flags().is_static()) {
1299       fieldDescriptor& fd = fs.field_descriptor();
1300       cl->do_field(&fd);
1301     }
1302   }
1303 }
1304 
1305 
1306 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
1307   instanceKlassHandle h_this(THREAD, this);
1308   do_local_static_fields_impl(h_this, f, mirror, CHECK);
1309 }
1310 
1311 
1312 void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_k,
1313                              void f(fieldDescriptor* fd, Handle, TRAPS), Handle mirror, TRAPS) {
1314   for (JavaFieldStream fs(this_k()); !fs.done(); fs.next()) {
1315     if (fs.access_flags().is_static()) {
1316       fieldDescriptor& fd = fs.field_descriptor();
1317       f(&fd, mirror, CHECK);
1318     }
1319   }
1320 }
1321 
1322 
1323 static int compare_fields_by_offset(int* a, int* b) {
1324   return a[0] - b[0];
1325 }
1326 
1327 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
1328   InstanceKlass* super = superklass();
1329   if (super != NULL) {
1330     super->do_nonstatic_fields(cl);
1331   }
1332   fieldDescriptor fd;
1333   int length = java_fields_count();
1334   // In DebugInfo nonstatic fields are sorted by offset.
1335   int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
1336   int j = 0;
1337   for (int i = 0; i < length; i += 1) {
1338     fd.reinitialize(this, i);
1339     if (!fd.is_static()) {
1340       fields_sorted[j + 0] = fd.offset();
1341       fields_sorted[j + 1] = i;
1342       j += 2;
1343     }
1344   }
1345   if (j > 0) {
1346     length = j;
1347     // _sort_Fn is defined in growableArray.hpp.
1348     qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
1349     for (int i = 0; i < length; i += 2) {
1350       fd.reinitialize(this, fields_sorted[i + 1]);
1351       assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
1352       cl->do_field(&fd);
1353     }
1354   }
1355   FREE_C_HEAP_ARRAY(int, fields_sorted, mtClass);
1356 }
1357 
1358 
1359 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
1360   if (array_klasses() != NULL)
1361     ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
1362 }
1363 
1364 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
1365   if (array_klasses() != NULL)
1366     ArrayKlass::cast(array_klasses())->array_klasses_do(f);
1367 }
1368 
1369 #ifdef ASSERT
1370 static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {
1371   int len = methods->length();
1372   for (int index = 0; index < len; index++) {
1373     Method* m = methods->at(index);
1374     assert(m->is_method(), "must be method");
1375     if (m->signature() == signature && m->name() == name) {
1376        return index;
1377     }
1378   }
1379   return -1;
1380 }
1381 #endif
1382 
1383 static int binary_search(Array<Method*>* methods, Symbol* name) {
1384   int len = methods->length();
1385   // methods are sorted, so do binary search
1386   int l = 0;
1387   int h = len - 1;
1388   while (l <= h) {
1389     int mid = (l + h) >> 1;
1390     Method* m = methods->at(mid);
1391     assert(m->is_method(), "must be method");
1392     int res = m->name()->fast_compare(name);
1393     if (res == 0) {
1394       return mid;
1395     } else if (res < 0) {
1396       l = mid + 1;
1397     } else {
1398       h = mid - 1;
1399     }
1400   }
1401   return -1;
1402 }
1403 
1404 // find_method looks up the name/signature in the local methods array
1405 Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {
1406   return find_method_impl(name, signature, false);
1407 }
1408 
1409 Method* InstanceKlass::find_method_impl(Symbol* name, Symbol* signature, bool skipping_overpass) const {
1410   return InstanceKlass::find_method_impl(methods(), name, signature, skipping_overpass);
1411 }
1412 
1413 // find_instance_method looks up the name/signature in the local methods array
1414 // and skips over static methods
1415 Method* InstanceKlass::find_instance_method(
1416     Array<Method*>* methods, Symbol* name, Symbol* signature) {
1417   Method* meth = InstanceKlass::find_method(methods, name, signature);
1418   if (meth != NULL && meth->is_static()) {
1419       meth = NULL;
1420   }
1421   return meth;
1422 }
1423 
1424 // find_method looks up the name/signature in the local methods array
1425 Method* InstanceKlass::find_method(
1426     Array<Method*>* methods, Symbol* name, Symbol* signature) {
1427   return InstanceKlass::find_method_impl(methods, name, signature, false);
1428 }
1429 
1430 Method* InstanceKlass::find_method_impl(
1431     Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass) {
1432   int hit = find_method_index(methods, name, signature, skipping_overpass);
1433   return hit >= 0 ? methods->at(hit): NULL;
1434 }
1435 
1436 // Used directly for default_methods to find the index into the
1437 // default_vtable_indices, and indirectly by find_method
1438 // find_method_index looks in the local methods array to return the index
1439 // of the matching name/signature. If, overpass methods are being ignored,
1440 // the search continues to find a potential non-overpass match.  This capability
1441 // is important during method resolution to prefer a static method, for example,
1442 // over an overpass method.
1443 int InstanceKlass::find_method_index(
1444     Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass) {
1445   int hit = binary_search(methods, name);
1446   if (hit != -1) {
1447     Method* m = methods->at(hit);
1448     // Do linear search to find matching signature.  First, quick check
1449     // for common case, ignoring overpasses if requested.
1450     if ((m->signature() == signature) && (!skipping_overpass || !m->is_overpass())) return hit;
1451 
1452     // search downwards through overloaded methods
1453     int i;
1454     for (i = hit - 1; i >= 0; --i) {
1455         Method* m = methods->at(i);
1456         assert(m->is_method(), "must be method");
1457         if (m->name() != name) break;
1458         if ((m->signature() == signature) && (!skipping_overpass || !m->is_overpass())) return i;
1459     }
1460     // search upwards
1461     for (i = hit + 1; i < methods->length(); ++i) {
1462         Method* m = methods->at(i);
1463         assert(m->is_method(), "must be method");
1464         if (m->name() != name) break;
1465         if ((m->signature() == signature) && (!skipping_overpass || !m->is_overpass())) return i;
1466     }
1467     // not found
1468 #ifdef ASSERT
1469     int index = skipping_overpass ? -1 : linear_search(methods, name, signature);
1470     assert(index == -1, err_msg("binary search should have found entry %d", index));
1471 #endif
1472   }
1473   return -1;
1474 }
1475 int InstanceKlass::find_method_by_name(Symbol* name, int* end) {
1476   return find_method_by_name(methods(), name, end);
1477 }
1478 
1479 int InstanceKlass::find_method_by_name(
1480     Array<Method*>* methods, Symbol* name, int* end_ptr) {
1481   assert(end_ptr != NULL, "just checking");
1482   int start = binary_search(methods, name);
1483   int end = start + 1;
1484   if (start != -1) {
1485     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
1486     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
1487     *end_ptr = end;
1488     return start;
1489   }
1490   return -1;
1491 }
1492 
1493 // uncached_lookup_method searches both the local class methods array and all
1494 // superclasses methods arrays, skipping any overpass methods in superclasses.
1495 Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const {
1496   MethodLookupMode lookup_mode = mode;
1497   Klass* klass = const_cast<InstanceKlass*>(this);
1498   while (klass != NULL) {
1499     Method* method = InstanceKlass::cast(klass)->find_method_impl(name, signature, (lookup_mode == skip_overpass));
1500     if (method != NULL) {
1501       return method;
1502     }
1503     klass = InstanceKlass::cast(klass)->super();
1504     lookup_mode = skip_overpass;   // Always ignore overpass methods in superclasses
1505   }
1506   return NULL;
1507 }
1508 
1509 #ifdef ASSERT
1510 // search through class hierarchy and return true if this class or
1511 // one of the superclasses was redefined
1512 bool InstanceKlass::has_redefined_this_or_super() const {
1513   const InstanceKlass* klass = this;
1514   while (klass != NULL) {
1515     if (klass->has_been_redefined()) {
1516       return true;
1517     }
1518     klass = InstanceKlass::cast(klass->super());
1519   }
1520   return false;
1521 }
1522 #endif
1523 
1524 // lookup a method in the default methods list then in all transitive interfaces
1525 // Do NOT return private or static methods
1526 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
1527                                                          Symbol* signature) const {
1528   Method* m = NULL;
1529   if (default_methods() != NULL) {
1530     m = find_method(default_methods(), name, signature);
1531   }
1532   // Look up interfaces
1533   if (m == NULL) {
1534     m = lookup_method_in_all_interfaces(name, signature, normal);
1535   }
1536   return m;
1537 }
1538 
1539 // lookup a method in all the interfaces that this class implements
1540 // Do NOT return private or static methods, new in JDK8 which are not externally visible
1541 // They should only be found in the initial InterfaceMethodRef
1542 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
1543                                                        Symbol* signature,
1544                                                        MethodLookupMode mode) const {
1545   Array<Klass*>* all_ifs = transitive_interfaces();
1546   int num_ifs = all_ifs->length();
1547   InstanceKlass *ik = NULL;
1548   for (int i = 0; i < num_ifs; i++) {
1549     ik = InstanceKlass::cast(all_ifs->at(i));
1550     Method* m = ik->lookup_method(name, signature);
1551     if (m != NULL && m->is_public() && !m->is_static() &&
1552         ((mode != skip_defaults) || !m->is_default_method())) {
1553       return m;
1554     }
1555   }
1556   return NULL;
1557 }
1558 
1559 /* jni_id_for_impl for jfieldIds only */
1560 JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_k, int offset) {
1561   MutexLocker ml(JfieldIdCreation_lock);
1562   // Retry lookup after we got the lock
1563   JNIid* probe = this_k->jni_ids() == NULL ? NULL : this_k->jni_ids()->find(offset);
1564   if (probe == NULL) {
1565     // Slow case, allocate new static field identifier
1566     probe = new JNIid(this_k(), offset, this_k->jni_ids());
1567     this_k->set_jni_ids(probe);
1568   }
1569   return probe;
1570 }
1571 
1572 
1573 /* jni_id_for for jfieldIds only */
1574 JNIid* InstanceKlass::jni_id_for(int offset) {
1575   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
1576   if (probe == NULL) {
1577     probe = jni_id_for_impl(this, offset);
1578   }
1579   return probe;
1580 }
1581 
1582 u2 InstanceKlass::enclosing_method_data(int offset) {
1583   Array<jushort>* inner_class_list = inner_classes();
1584   if (inner_class_list == NULL) {
1585     return 0;
1586   }
1587   int length = inner_class_list->length();
1588   if (length % inner_class_next_offset == 0) {
1589     return 0;
1590   } else {
1591     int index = length - enclosing_method_attribute_size;
1592     assert(offset < enclosing_method_attribute_size, "invalid offset");
1593     return inner_class_list->at(index + offset);
1594   }
1595 }
1596 
1597 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
1598                                                  u2 method_index) {
1599   Array<jushort>* inner_class_list = inner_classes();
1600   assert (inner_class_list != NULL, "_inner_classes list is not set up");
1601   int length = inner_class_list->length();
1602   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
1603     int index = length - enclosing_method_attribute_size;
1604     inner_class_list->at_put(
1605       index + enclosing_method_class_index_offset, class_index);
1606     inner_class_list->at_put(
1607       index + enclosing_method_method_index_offset, method_index);
1608   }
1609 }
1610 
1611 // Lookup or create a jmethodID.
1612 // This code is called by the VMThread and JavaThreads so the
1613 // locking has to be done very carefully to avoid deadlocks
1614 // and/or other cache consistency problems.
1615 //
1616 jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {
1617   size_t idnum = (size_t)method_h->method_idnum();
1618   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
1619   size_t length = 0;
1620   jmethodID id = NULL;
1621 
1622   // We use a double-check locking idiom here because this cache is
1623   // performance sensitive. In the normal system, this cache only
1624   // transitions from NULL to non-NULL which is safe because we use
1625   // release_set_methods_jmethod_ids() to advertise the new cache.
1626   // A partially constructed cache should never be seen by a racing
1627   // thread. We also use release_store_ptr() to save a new jmethodID
1628   // in the cache so a partially constructed jmethodID should never be
1629   // seen either. Cache reads of existing jmethodIDs proceed without a
1630   // lock, but cache writes of a new jmethodID requires uniqueness and
1631   // creation of the cache itself requires no leaks so a lock is
1632   // generally acquired in those two cases.
1633   //
1634   // If the RedefineClasses() API has been used, then this cache can
1635   // grow and we'll have transitions from non-NULL to bigger non-NULL.
1636   // Cache creation requires no leaks and we require safety between all
1637   // cache accesses and freeing of the old cache so a lock is generally
1638   // acquired when the RedefineClasses() API has been used.
1639 
1640   if (jmeths != NULL) {
1641     // the cache already exists
1642     if (!ik_h->idnum_can_increment()) {
1643       // the cache can't grow so we can just get the current values
1644       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1645     } else {
1646       // cache can grow so we have to be more careful
1647       if (Threads::number_of_threads() == 0 ||
1648           SafepointSynchronize::is_at_safepoint()) {
1649         // we're single threaded or at a safepoint - no locking needed
1650         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1651       } else {
1652         MutexLocker ml(JmethodIdCreation_lock);
1653         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1654       }
1655     }
1656   }
1657   // implied else:
1658   // we need to allocate a cache so default length and id values are good
1659 
1660   if (jmeths == NULL ||   // no cache yet
1661       length <= idnum ||  // cache is too short
1662       id == NULL) {       // cache doesn't contain entry
1663 
1664     // This function can be called by the VMThread so we have to do all
1665     // things that might block on a safepoint before grabbing the lock.
1666     // Otherwise, we can deadlock with the VMThread or have a cache
1667     // consistency issue. These vars keep track of what we might have
1668     // to free after the lock is dropped.
1669     jmethodID  to_dealloc_id     = NULL;
1670     jmethodID* to_dealloc_jmeths = NULL;
1671 
1672     // may not allocate new_jmeths or use it if we allocate it
1673     jmethodID* new_jmeths = NULL;
1674     if (length <= idnum) {
1675       // allocate a new cache that might be used
1676       size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
1677       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
1678       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
1679       // cache size is stored in element[0], other elements offset by one
1680       new_jmeths[0] = (jmethodID)size;
1681     }
1682 
1683     // allocate a new jmethodID that might be used
1684     jmethodID new_id = NULL;
1685     if (method_h->is_old() && !method_h->is_obsolete()) {
1686       // The method passed in is old (but not obsolete), we need to use the current version
1687       Method* current_method = ik_h->method_with_idnum((int)idnum);
1688       assert(current_method != NULL, "old and but not obsolete, so should exist");
1689       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);
1690     } else {
1691       // It is the current version of the method or an obsolete method,
1692       // use the version passed in
1693       new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());
1694     }
1695 
1696     if (Threads::number_of_threads() == 0 ||
1697         SafepointSynchronize::is_at_safepoint()) {
1698       // we're single threaded or at a safepoint - no locking needed
1699       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
1700                                           &to_dealloc_id, &to_dealloc_jmeths);
1701     } else {
1702       MutexLocker ml(JmethodIdCreation_lock);
1703       id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
1704                                           &to_dealloc_id, &to_dealloc_jmeths);
1705     }
1706 
1707     // The lock has been dropped so we can free resources.
1708     // Free up either the old cache or the new cache if we allocated one.
1709     if (to_dealloc_jmeths != NULL) {
1710       FreeHeap(to_dealloc_jmeths);
1711     }
1712     // free up the new ID since it wasn't needed
1713     if (to_dealloc_id != NULL) {
1714       Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);
1715     }
1716   }
1717   return id;
1718 }
1719 
1720 
1721 // Common code to fetch the jmethodID from the cache or update the
1722 // cache with the new jmethodID. This function should never do anything
1723 // that causes the caller to go to a safepoint or we can deadlock with
1724 // the VMThread or have cache consistency issues.
1725 //
1726 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
1727             instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,
1728             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
1729             jmethodID** to_dealloc_jmeths_p) {
1730   assert(new_id != NULL, "sanity check");
1731   assert(to_dealloc_id_p != NULL, "sanity check");
1732   assert(to_dealloc_jmeths_p != NULL, "sanity check");
1733   assert(Threads::number_of_threads() == 0 ||
1734          SafepointSynchronize::is_at_safepoint() ||
1735          JmethodIdCreation_lock->owned_by_self(), "sanity check");
1736 
1737   // reacquire the cache - we are locked, single threaded or at a safepoint
1738   jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
1739   jmethodID  id     = NULL;
1740   size_t     length = 0;
1741 
1742   if (jmeths == NULL ||                         // no cache yet
1743       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
1744     if (jmeths != NULL) {
1745       // copy any existing entries from the old cache
1746       for (size_t index = 0; index < length; index++) {
1747         new_jmeths[index+1] = jmeths[index+1];
1748       }
1749       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
1750     }
1751     ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
1752   } else {
1753     // fetch jmethodID (if any) from the existing cache
1754     id = jmeths[idnum+1];
1755     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
1756   }
1757   if (id == NULL) {
1758     // No matching jmethodID in the existing cache or we have a new
1759     // cache or we just grew the cache. This cache write is done here
1760     // by the first thread to win the foot race because a jmethodID
1761     // needs to be unique once it is generally available.
1762     id = new_id;
1763 
1764     // The jmethodID cache can be read while unlocked so we have to
1765     // make sure the new jmethodID is complete before installing it
1766     // in the cache.
1767     OrderAccess::release_store_ptr(&jmeths[idnum+1], id);
1768   } else {
1769     *to_dealloc_id_p = new_id; // save new id for later delete
1770   }
1771   return id;
1772 }
1773 
1774 
1775 // Common code to get the jmethodID cache length and the jmethodID
1776 // value at index idnum if there is one.
1777 //
1778 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
1779        size_t idnum, size_t *length_p, jmethodID* id_p) {
1780   assert(cache != NULL, "sanity check");
1781   assert(length_p != NULL, "sanity check");
1782   assert(id_p != NULL, "sanity check");
1783 
1784   // cache size is stored in element[0], other elements offset by one
1785   *length_p = (size_t)cache[0];
1786   if (*length_p <= idnum) {  // cache is too short
1787     *id_p = NULL;
1788   } else {
1789     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
1790   }
1791 }
1792 
1793 
1794 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
1795 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
1796   size_t idnum = (size_t)method->method_idnum();
1797   jmethodID* jmeths = methods_jmethod_ids_acquire();
1798   size_t length;                                // length assigned as debugging crumb
1799   jmethodID id = NULL;
1800   if (jmeths != NULL &&                         // If there is a cache
1801       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
1802     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
1803   }
1804   return id;
1805 }
1806 
1807 int nmethodBucket::decrement() {
1808   return Atomic::add(-1, (volatile int *)&_count);
1809 }
1810 
1811 //
1812 // Walk the list of dependent nmethods searching for nmethods which
1813 // are dependent on the changes that were passed in and mark them for
1814 // deoptimization.  Returns the number of nmethods found.
1815 //
1816 int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {
1817   assert_locked_or_safepoint(CodeCache_lock);
1818   int found = 0;
1819   nmethodBucket* b = _dependencies;
1820   while (b != NULL) {
1821     nmethod* nm = b->get_nmethod();
1822     // since dependencies aren't removed until an nmethod becomes a zombie,
1823     // the dependency list may contain nmethods which aren't alive.
1824     if (b->count() > 0 && nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
1825       if (TraceDependencies) {
1826         ResourceMark rm;
1827         tty->print_cr("Marked for deoptimization");
1828         tty->print_cr("  context = %s", this->external_name());
1829         changes.print();
1830         nm->print();
1831         nm->print_dependencies();
1832       }
1833       nm->mark_for_deoptimization();
1834       found++;
1835     }
1836     b = b->next();
1837   }
1838   return found;
1839 }
1840 
1841 void InstanceKlass::clean_dependent_nmethods() {
1842   assert_locked_or_safepoint(CodeCache_lock);
1843 
1844   if (has_unloaded_dependent()) {
1845     nmethodBucket* b = _dependencies;
1846     nmethodBucket* last = NULL;
1847     while (b != NULL) {
1848       assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));
1849 
1850       nmethodBucket* next = b->next();
1851 
1852       if (b->count() == 0) {
1853         if (last == NULL) {
1854           _dependencies = next;
1855         } else {
1856           last->set_next(next);
1857         }
1858         delete b;
1859         // last stays the same.
1860       } else {
1861         last = b;
1862       }
1863 
1864       b = next;
1865     }
1866     set_has_unloaded_dependent(false);
1867   }
1868 #ifdef ASSERT
1869   else {
1870     // Verification
1871     for (nmethodBucket* b = _dependencies; b != NULL; b = b->next()) {
1872       assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));
1873       assert(b->count() != 0, "empty buckets need to be cleaned");
1874     }
1875   }
1876 #endif
1877 }
1878 
1879 //
1880 // Add an nmethodBucket to the list of dependencies for this nmethod.
1881 // It's possible that an nmethod has multiple dependencies on this klass
1882 // so a count is kept for each bucket to guarantee that creation and
1883 // deletion of dependencies is consistent.
1884 //
1885 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
1886   assert_locked_or_safepoint(CodeCache_lock);
1887   nmethodBucket* b = _dependencies;
1888   nmethodBucket* last = NULL;
1889   while (b != NULL) {
1890     if (nm == b->get_nmethod()) {
1891       b->increment();
1892       return;
1893     }
1894     b = b->next();
1895   }
1896   _dependencies = new nmethodBucket(nm, _dependencies);
1897 }
1898 
1899 
1900 //
1901 // Decrement count of the nmethod in the dependency list and remove
1902 // the bucket competely when the count goes to 0.  This method must
1903 // find a corresponding bucket otherwise there's a bug in the
1904 // recording of dependecies.
1905 //
1906 void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
1907   assert_locked_or_safepoint(CodeCache_lock);
1908   nmethodBucket* b = _dependencies;
1909   nmethodBucket* last = NULL;
1910   while (b != NULL) {
1911     if (nm == b->get_nmethod()) {
1912       int val = b->decrement();
1913       guarantee(val >= 0, err_msg("Underflow: %d", val));
1914       if (val == 0) {
1915         set_has_unloaded_dependent(true);
1916       }
1917       return;
1918     }
1919     last = b;
1920     b = b->next();
1921   }
1922 #ifdef ASSERT
1923   tty->print_cr("### %s can't find dependent nmethod:", this->external_name());
1924   nm->print();
1925 #endif // ASSERT
1926   ShouldNotReachHere();
1927 }
1928 
1929 
1930 #ifndef PRODUCT
1931 void InstanceKlass::print_dependent_nmethods(bool verbose) {
1932   nmethodBucket* b = _dependencies;
1933   int idx = 0;
1934   while (b != NULL) {
1935     nmethod* nm = b->get_nmethod();
1936     tty->print("[%d] count=%d { ", idx++, b->count());
1937     if (!verbose) {
1938       nm->print_on(tty, "nmethod");
1939       tty->print_cr(" } ");
1940     } else {
1941       nm->print();
1942       nm->print_dependencies();
1943       tty->print_cr("--- } ");
1944     }
1945     b = b->next();
1946   }
1947 }
1948 
1949 
1950 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
1951   nmethodBucket* b = _dependencies;
1952   while (b != NULL) {
1953     if (nm == b->get_nmethod()) {
1954 #ifdef ASSERT
1955       int count = b->count();
1956       assert(count >= 0, err_msg("count shouldn't be negative: %d", count));
1957 #endif
1958       return true;
1959     }
1960     b = b->next();
1961   }
1962   return false;
1963 }
1964 #endif //PRODUCT
1965 
1966 
1967 // Garbage collection
1968 
1969 #ifdef ASSERT
1970 template <class T> void assert_is_in(T *p) {
1971   T heap_oop = oopDesc::load_heap_oop(p);
1972   if (!oopDesc::is_null(heap_oop)) {
1973     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
1974     assert(Universe::heap()->is_in(o), "should be in heap");
1975   }
1976 }
1977 template <class T> void assert_is_in_closed_subset(T *p) {
1978   T heap_oop = oopDesc::load_heap_oop(p);
1979   if (!oopDesc::is_null(heap_oop)) {
1980     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
1981     assert(Universe::heap()->is_in_closed_subset(o),
1982            err_msg("should be in closed *p " INTPTR_FORMAT " " INTPTR_FORMAT, (address)p, (address)o));
1983   }
1984 }
1985 template <class T> void assert_is_in_reserved(T *p) {
1986   T heap_oop = oopDesc::load_heap_oop(p);
1987   if (!oopDesc::is_null(heap_oop)) {
1988     oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
1989     assert(Universe::heap()->is_in_reserved(o), "should be in reserved");
1990   }
1991 }
1992 template <class T> void assert_nothing(T *p) {}
1993 
1994 #else
1995 template <class T> void assert_is_in(T *p) {}
1996 template <class T> void assert_is_in_closed_subset(T *p) {}
1997 template <class T> void assert_is_in_reserved(T *p) {}
1998 template <class T> void assert_nothing(T *p) {}
1999 #endif // ASSERT
2000 
2001 //
2002 // Macros that iterate over areas of oops which are specialized on type of
2003 // oop pointer either narrow or wide, depending on UseCompressedOops
2004 //
2005 // Parameters are:
2006 //   T         - type of oop to point to (either oop or narrowOop)
2007 //   start_p   - starting pointer for region to iterate over
2008 //   count     - number of oops or narrowOops to iterate over
2009 //   do_oop    - action to perform on each oop (it's arbitrary C code which
2010 //               makes it more efficient to put in a macro rather than making
2011 //               it a template function)
2012 //   assert_fn - assert function which is template function because performance
2013 //               doesn't matter when enabled.
2014 #define InstanceKlass_SPECIALIZED_OOP_ITERATE( \
2015   T, start_p, count, do_oop,                \
2016   assert_fn)                                \
2017 {                                           \
2018   T* p         = (T*)(start_p);             \
2019   T* const end = p + (count);               \
2020   while (p < end) {                         \
2021     (assert_fn)(p);                         \
2022     do_oop;                                 \
2023     ++p;                                    \
2024   }                                         \
2025 }
2026 
2027 #define InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE( \
2028   T, start_p, count, do_oop,                \
2029   assert_fn)                                \
2030 {                                           \
2031   T* const start = (T*)(start_p);           \
2032   T*       p     = start + (count);         \
2033   while (start < p) {                       \
2034     --p;                                    \
2035     (assert_fn)(p);                         \
2036     do_oop;                                 \
2037   }                                         \
2038 }
2039 
2040 #define InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE( \
2041   T, start_p, count, low, high,             \
2042   do_oop, assert_fn)                        \
2043 {                                           \
2044   T* const l = (T*)(low);                   \
2045   T* const h = (T*)(high);                  \
2046   assert(mask_bits((intptr_t)l, sizeof(T)-1) == 0 && \
2047          mask_bits((intptr_t)h, sizeof(T)-1) == 0,   \
2048          "bounded region must be properly aligned"); \
2049   T* p       = (T*)(start_p);               \
2050   T* end     = p + (count);                 \
2051   if (p < l) p = l;                         \
2052   if (end > h) end = h;                     \
2053   while (p < end) {                         \
2054     (assert_fn)(p);                         \
2055     do_oop;                                 \
2056     ++p;                                    \
2057   }                                         \
2058 }
2059 
2060 
2061 // The following macros call specialized macros, passing either oop or
2062 // narrowOop as the specialization type.  These test the UseCompressedOops
2063 // flag.
2064 #define InstanceKlass_OOP_MAP_ITERATE(obj, do_oop, assert_fn)            \
2065 {                                                                        \
2066   /* Compute oopmap block range. The common case                         \
2067      is nonstatic_oop_map_size == 1. */                                  \
2068   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
2069   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
2070   if (UseCompressedOops) {                                               \
2071     while (map < end_map) {                                              \
2072       InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop,                   \
2073         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
2074         do_oop, assert_fn)                                               \
2075       ++map;                                                             \
2076     }                                                                    \
2077   } else {                                                               \
2078     while (map < end_map) {                                              \
2079       InstanceKlass_SPECIALIZED_OOP_ITERATE(oop,                         \
2080         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
2081         do_oop, assert_fn)                                               \
2082       ++map;                                                             \
2083     }                                                                    \
2084   }                                                                      \
2085 }
2086 
2087 #define InstanceKlass_OOP_MAP_REVERSE_ITERATE(obj, do_oop, assert_fn)    \
2088 {                                                                        \
2089   OopMapBlock* const start_map = start_of_nonstatic_oop_maps();          \
2090   OopMapBlock* map             = start_map + nonstatic_oop_map_count();  \
2091   if (UseCompressedOops) {                                               \
2092     while (start_map < map) {                                            \
2093       --map;                                                             \
2094       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop,           \
2095         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
2096         do_oop, assert_fn)                                               \
2097     }                                                                    \
2098   } else {                                                               \
2099     while (start_map < map) {                                            \
2100       --map;                                                             \
2101       InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop,                 \
2102         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
2103         do_oop, assert_fn)                                               \
2104     }                                                                    \
2105   }                                                                      \
2106 }
2107 
2108 #define InstanceKlass_BOUNDED_OOP_MAP_ITERATE(obj, low, high, do_oop,    \
2109                                               assert_fn)                 \
2110 {                                                                        \
2111   /* Compute oopmap block range. The common case is                      \
2112      nonstatic_oop_map_size == 1, so we accept the                       \
2113      usually non-existent extra overhead of examining                    \
2114      all the maps. */                                                    \
2115   OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
2116   OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
2117   if (UseCompressedOops) {                                               \
2118     while (map < end_map) {                                              \
2119       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop,           \
2120         obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
2121         low, high,                                                       \
2122         do_oop, assert_fn)                                               \
2123       ++map;                                                             \
2124     }                                                                    \
2125   } else {                                                               \
2126     while (map < end_map) {                                              \
2127       InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop,                 \
2128         obj->obj_field_addr<oop>(map->offset()), map->count(),           \
2129         low, high,                                                       \
2130         do_oop, assert_fn)                                               \
2131       ++map;                                                             \
2132     }                                                                    \
2133   }                                                                      \
2134 }
2135 
2136 void InstanceKlass::oop_follow_contents(oop obj) {
2137   assert(obj != NULL, "can't follow the content of NULL object");
2138   MarkSweep::follow_klass(obj->klass());
2139   InstanceKlass_OOP_MAP_ITERATE( \
2140     obj, \
2141     MarkSweep::mark_and_push(p), \
2142     assert_is_in_closed_subset)
2143 }
2144 
2145 #if INCLUDE_ALL_GCS
2146 void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,
2147                                         oop obj) {
2148   assert(obj != NULL, "can't follow the content of NULL object");
2149   PSParallelCompact::follow_klass(cm, obj->klass());
2150   // Only mark the header and let the scan of the meta-data mark
2151   // everything else.
2152   InstanceKlass_OOP_MAP_ITERATE( \
2153     obj, \
2154     PSParallelCompact::mark_and_push(cm, p), \
2155     assert_is_in)
2156 }
2157 #endif // INCLUDE_ALL_GCS
2158 
2159 // closure's do_metadata() method dictates whether the given closure should be
2160 // applied to the klass ptr in the object header.
2161 
2162 #define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)        \
2163                                                                              \
2164 int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \
2165   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
2166   /* header */                                                          \
2167   if_do_metadata_checked(closure, nv_suffix) {                          \
2168     closure->do_klass##nv_suffix(obj->klass());                         \
2169   }                                                                     \
2170   InstanceKlass_OOP_MAP_ITERATE(                                        \
2171     obj,                                                                \
2172     SpecializationStats::                                               \
2173       record_do_oop_call##nv_suffix(SpecializationStats::ik);           \
2174     (closure)->do_oop##nv_suffix(p),                                    \
2175     assert_is_in_closed_subset)                                         \
2176   return size_helper();                                                 \
2177 }
2178 
2179 #if INCLUDE_ALL_GCS
2180 #define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
2181                                                                                 \
2182 int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj,                \
2183                                               OopClosureType* closure) {        \
2184   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \
2185                                                                                 \
2186   assert_should_ignore_metadata(closure, nv_suffix);                            \
2187                                                                                 \
2188   /* instance variables */                                                      \
2189   InstanceKlass_OOP_MAP_REVERSE_ITERATE(                                        \
2190     obj,                                                                        \
2191     SpecializationStats::record_do_oop_call##nv_suffix(SpecializationStats::ik);\
2192     (closure)->do_oop##nv_suffix(p),                                            \
2193     assert_is_in_closed_subset)                                                 \
2194    return size_helper();                                                        \
2195 }
2196 #endif // INCLUDE_ALL_GCS
2197 
2198 #define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \
2199                                                                         \
2200 int InstanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj,              \
2201                                                   OopClosureType* closure, \
2202                                                   MemRegion mr) {          \
2203   SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
2204   if_do_metadata_checked(closure, nv_suffix) {                           \
2205     if (mr.contains(obj)) {                                              \
2206       closure->do_klass##nv_suffix(obj->klass());                        \
2207     }                                                                    \
2208   }                                                                      \
2209   InstanceKlass_BOUNDED_OOP_MAP_ITERATE(                                 \
2210     obj, mr.start(), mr.end(),                                           \
2211     (closure)->do_oop##nv_suffix(p),                                     \
2212     assert_is_in_closed_subset)                                          \
2213   return size_helper();                                                  \
2214 }
2215 
2216 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)
2217 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)
2218 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
2219 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
2220 #if INCLUDE_ALL_GCS
2221 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
2222 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
2223 #endif // INCLUDE_ALL_GCS
2224 
2225 int InstanceKlass::oop_adjust_pointers(oop obj) {
2226   int size = size_helper();
2227   InstanceKlass_OOP_MAP_ITERATE( \
2228     obj, \
2229     MarkSweep::adjust_pointer(p), \
2230     assert_is_in)
2231   return size;
2232 }
2233 
2234 #if INCLUDE_ALL_GCS
2235 void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
2236   InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
2237     obj, \
2238     if (PSScavenge::should_scavenge(p)) { \
2239       pm->claim_or_forward_depth(p); \
2240     }, \
2241     assert_nothing )
2242 }
2243 
2244 int InstanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {
2245   int size = size_helper();
2246   InstanceKlass_OOP_MAP_ITERATE( \
2247     obj, \
2248     PSParallelCompact::adjust_pointer(p), \
2249     assert_is_in)
2250   return size;
2251 }
2252 
2253 #endif // INCLUDE_ALL_GCS
2254 
2255 void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
2256   assert(class_loader_data()->is_alive(is_alive), "this klass should be live");
2257   if (is_interface()) {
2258     if (ClassUnloading) {
2259       Klass* impl = implementor();
2260       if (impl != NULL) {
2261         if (!impl->is_loader_alive(is_alive)) {
2262           // remove this guy
2263           Klass** klass = adr_implementor();
2264           assert(klass != NULL, "null klass");
2265           if (klass != NULL) {
2266             *klass = NULL;
2267           }
2268         }
2269       }
2270     }
2271   }
2272 }
2273 
2274 void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {
2275   for (int m = 0; m < methods()->length(); m++) {
2276     MethodData* mdo = methods()->at(m)->method_data();
2277     if (mdo != NULL) {
2278       mdo->clean_method_data(is_alive);
2279     }
2280   }
2281 }
2282 
2283 
2284 static void remove_unshareable_in_class(Klass* k) {
2285   // remove klass's unshareable info
2286   k->remove_unshareable_info();
2287 }
2288 
2289 void InstanceKlass::remove_unshareable_info() {
2290   Klass::remove_unshareable_info();
2291   // Unlink the class
2292   if (is_linked()) {
2293     unlink_class();
2294   }
2295   init_implementor();
2296 
2297   constants()->remove_unshareable_info();
2298 
2299   for (int i = 0; i < methods()->length(); i++) {
2300     Method* m = methods()->at(i);
2301     m->remove_unshareable_info();
2302   }
2303 
2304   // do array classes also.
2305   array_klasses_do(remove_unshareable_in_class);
2306 }
2307 
2308 static void restore_unshareable_in_class(Klass* k, TRAPS) {
2309   // Array classes have null protection domain.
2310   // --> see ArrayKlass::complete_create_array_klass()
2311   k->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);
2312 }
2313 
2314 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
2315   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2316   instanceKlassHandle ik(THREAD, this);
2317 
2318   Array<Method*>* methods = ik->methods();
2319   int num_methods = methods->length();
2320   for (int index2 = 0; index2 < num_methods; ++index2) {
2321     methodHandle m(THREAD, methods->at(index2));
2322     m->restore_unshareable_info(CHECK);
2323   }
2324   if (JvmtiExport::has_redefined_a_class()) {
2325     // Reinitialize vtable because RedefineClasses may have changed some
2326     // entries in this vtable for super classes so the CDS vtable might
2327     // point to old or obsolete entries.  RedefineClasses doesn't fix up
2328     // vtables in the shared system dictionary, only the main one.
2329     // It also redefines the itable too so fix that too.
2330     ResourceMark rm(THREAD);
2331     ik->vtable()->initialize_vtable(false, CHECK);
2332     ik->itable()->initialize_itable(false, CHECK);
2333   }
2334 
2335   // restore constant pool resolved references
2336   ik->constants()->restore_unshareable_info(CHECK);
2337 
2338   ik->array_klasses_do(restore_unshareable_in_class, CHECK);
2339 }
2340 
2341 // returns true IFF is_in_error_state() has been changed as a result of this call.
2342 bool InstanceKlass::check_sharing_error_state() {
2343   assert(DumpSharedSpaces, "should only be called during dumping");
2344   bool old_state = is_in_error_state();
2345 
2346   if (!is_in_error_state()) {
2347     bool bad = false;
2348     for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) {
2349       if (sup->is_in_error_state()) {
2350         bad = true;
2351         break;
2352       }
2353     }
2354     if (!bad) {
2355       Array<Klass*>* interfaces = transitive_interfaces();
2356       for (int i = 0; i < interfaces->length(); i++) {
2357         Klass* iface = interfaces->at(i);
2358         if (InstanceKlass::cast(iface)->is_in_error_state()) {
2359           bad = true;
2360           break;
2361         }
2362       }
2363     }
2364 
2365     if (bad) {
2366       set_in_error_state();
2367     }
2368   }
2369 
2370   return (old_state != is_in_error_state());
2371 }
2372 
2373 static void clear_all_breakpoints(Method* m) {
2374   m->clear_all_breakpoints();
2375 }
2376 
2377 
2378 void InstanceKlass::notify_unload_class(InstanceKlass* ik) {
2379   // notify the debugger
2380   if (JvmtiExport::should_post_class_unload()) {
2381     JvmtiExport::post_class_unload(ik);
2382   }
2383 
2384   // notify ClassLoadingService of class unload
2385   ClassLoadingService::notify_class_unloaded(ik);
2386 }
2387 
2388 void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {
2389   // Clean up C heap
2390   ik->release_C_heap_structures();
2391   ik->constants()->release_C_heap_structures();
2392 }
2393 
2394 void InstanceKlass::release_C_heap_structures() {
2395 
2396   // Can't release the constant pool here because the constant pool can be
2397   // deallocated separately from the InstanceKlass for default methods and
2398   // redefine classes.
2399 
2400   // Deallocate oop map cache
2401   if (_oop_map_cache != NULL) {
2402     delete _oop_map_cache;
2403     _oop_map_cache = NULL;
2404   }
2405 
2406   // Deallocate JNI identifiers for jfieldIDs
2407   JNIid::deallocate(jni_ids());
2408   set_jni_ids(NULL);
2409 
2410   jmethodID* jmeths = methods_jmethod_ids_acquire();
2411   if (jmeths != (jmethodID*)NULL) {
2412     release_set_methods_jmethod_ids(NULL);
2413     FreeHeap(jmeths);
2414   }
2415 
2416   // Deallocate MemberNameTable
2417   {
2418     Mutex* lock_or_null = SafepointSynchronize::is_at_safepoint() ? NULL : MemberNameTable_lock;
2419     MutexLockerEx ml(lock_or_null, Mutex::_no_safepoint_check_flag);
2420     MemberNameTable* mnt = member_names();
2421     if (mnt != NULL) {
2422       delete mnt;
2423       set_member_names(NULL);
2424     }
2425   }
2426 
2427   // release dependencies
2428   nmethodBucket* b = _dependencies;
2429   _dependencies = NULL;
2430   while (b != NULL) {
2431     nmethodBucket* next = b->next();
2432     delete b;
2433     b = next;
2434   }
2435 
2436   // Deallocate breakpoint records
2437   if (breakpoints() != 0x0) {
2438     methods_do(clear_all_breakpoints);
2439     assert(breakpoints() == 0x0, "should have cleared breakpoints");
2440   }
2441 
2442   // deallocate the cached class file
2443   if (_cached_class_file != NULL) {
2444     os::free(_cached_class_file, mtClass);
2445     _cached_class_file = NULL;
2446   }
2447 
2448   // Decrement symbol reference counts associated with the unloaded class.
2449   if (_name != NULL) _name->decrement_refcount();
2450   // unreference array name derived from this class name (arrays of an unloaded
2451   // class can't be referenced anymore).
2452   if (_array_name != NULL)  _array_name->decrement_refcount();
2453   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);
2454 
2455   assert(_total_instanceKlass_count >= 1, "Sanity check");
2456   Atomic::dec(&_total_instanceKlass_count);
2457 }
2458 
2459 void InstanceKlass::set_source_debug_extension(char* array, int length) {
2460   if (array == NULL) {
2461     _source_debug_extension = NULL;
2462   } else {
2463     // Adding one to the attribute length in order to store a null terminator
2464     // character could cause an overflow because the attribute length is
2465     // already coded with an u4 in the classfile, but in practice, it's
2466     // unlikely to happen.
2467     assert((length+1) > length, "Overflow checking");
2468     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2469     for (int i = 0; i < length; i++) {
2470       sde[i] = array[i];
2471     }
2472     sde[length] = '\0';
2473     _source_debug_extension = sde;
2474   }
2475 }
2476 
2477 address InstanceKlass::static_field_addr(int offset) {
2478   return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror()));
2479 }
2480 
2481 
2482 const char* InstanceKlass::signature_name() const {
2483   int hash_len = 0;
2484   char hash_buf[40];
2485 
2486   // If this is an anonymous class, append a hash to make the name unique
2487   if (is_anonymous()) {
2488     intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
2489     sprintf(hash_buf, "/" UINTX_FORMAT, (uintx)hash);
2490     hash_len = (int)strlen(hash_buf);
2491   }
2492 
2493   // Get the internal name as a c string
2494   const char* src = (const char*) (name()->as_C_string());
2495   const int src_length = (int)strlen(src);
2496 
2497   char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
2498 
2499   // Add L as type indicator
2500   int dest_index = 0;
2501   dest[dest_index++] = 'L';
2502 
2503   // Add the actual class name
2504   for (int src_index = 0; src_index < src_length; ) {
2505     dest[dest_index++] = src[src_index++];
2506   }
2507 
2508   // If we have a hash, append it
2509   for (int hash_index = 0; hash_index < hash_len; ) {
2510     dest[dest_index++] = hash_buf[hash_index++];
2511   }
2512 
2513   // Add the semicolon and the NULL
2514   dest[dest_index++] = ';';
2515   dest[dest_index] = '\0';
2516   return dest;
2517 }
2518 
2519 // different verisons of is_same_class_package
2520 bool InstanceKlass::is_same_class_package(Klass* class2) {
2521   Klass* class1 = this;
2522   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
2523   Symbol* classname1 = class1->name();
2524 
2525   if (class2->oop_is_objArray()) {
2526     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
2527   }
2528   oop classloader2;
2529   if (class2->oop_is_instance()) {
2530     classloader2 = InstanceKlass::cast(class2)->class_loader();
2531   } else {
2532     assert(class2->oop_is_typeArray(), "should be type array");
2533     classloader2 = NULL;
2534   }
2535   Symbol* classname2 = class2->name();
2536 
2537   return InstanceKlass::is_same_class_package(classloader1, classname1,
2538                                               classloader2, classname2);
2539 }
2540 
2541 bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
2542   Klass* class1 = this;
2543   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
2544   Symbol* classname1 = class1->name();
2545 
2546   return InstanceKlass::is_same_class_package(classloader1, classname1,
2547                                               classloader2, classname2);
2548 }
2549 
2550 // return true if two classes are in the same package, classloader
2551 // and classname information is enough to determine a class's package
2552 bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
2553                                           oop class_loader2, Symbol* class_name2) {
2554   if (class_loader1 != class_loader2) {
2555     return false;
2556   } else if (class_name1 == class_name2) {
2557     return true;                // skip painful bytewise comparison
2558   } else {
2559     ResourceMark rm;
2560 
2561     // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly
2562     // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
2563     // Otherwise, we just compare jbyte values between the strings.
2564     const jbyte *name1 = class_name1->base();
2565     const jbyte *name2 = class_name2->base();
2566 
2567     const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
2568     const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
2569 
2570     if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
2571       // One of the two doesn't have a package.  Only return true
2572       // if the other one also doesn't have a package.
2573       return last_slash1 == last_slash2;
2574     } else {
2575       // Skip over '['s
2576       if (*name1 == '[') {
2577         do {
2578           name1++;
2579         } while (*name1 == '[');
2580         if (*name1 != 'L') {
2581           // Something is terribly wrong.  Shouldn't be here.
2582           return false;
2583         }
2584       }
2585       if (*name2 == '[') {
2586         do {
2587           name2++;
2588         } while (*name2 == '[');
2589         if (*name2 != 'L') {
2590           // Something is terribly wrong.  Shouldn't be here.
2591           return false;
2592         }
2593       }
2594 
2595       // Check that package part is identical
2596       int length1 = last_slash1 - name1;
2597       int length2 = last_slash2 - name2;
2598 
2599       return UTF8::equal(name1, length1, name2, length2);
2600     }
2601   }
2602 }
2603 
2604 // Returns true iff super_method can be overridden by a method in targetclassname
2605 // See JSL 3rd edition 8.4.6.1
2606 // Assumes name-signature match
2607 // "this" is InstanceKlass of super_method which must exist
2608 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
2609 bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
2610    // Private methods can not be overridden
2611    if (super_method->is_private()) {
2612      return false;
2613    }
2614    // If super method is accessible, then override
2615    if ((super_method->is_protected()) ||
2616        (super_method->is_public())) {
2617      return true;
2618    }
2619    // Package-private methods are not inherited outside of package
2620    assert(super_method->is_package_private(), "must be package private");
2621    return(is_same_class_package(targetclassloader(), targetclassname));
2622 }
2623 
2624 /* defined for now in jvm.cpp, for historical reasons *--
2625 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
2626                                                      Symbol*& simple_name_result, TRAPS) {
2627   ...
2628 }
2629 */
2630 
2631 // tell if two classes have the same enclosing class (at package level)
2632 bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
2633                                                 Klass* class2_oop, TRAPS) {
2634   if (class2_oop == class1())                       return true;
2635   if (!class2_oop->oop_is_instance())  return false;
2636   instanceKlassHandle class2(THREAD, class2_oop);
2637 
2638   // must be in same package before we try anything else
2639   if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
2640     return false;
2641 
2642   // As long as there is an outer1.getEnclosingClass,
2643   // shift the search outward.
2644   instanceKlassHandle outer1 = class1;
2645   for (;;) {
2646     // As we walk along, look for equalities between outer1 and class2.
2647     // Eventually, the walks will terminate as outer1 stops
2648     // at the top-level class around the original class.
2649     bool ignore_inner_is_member;
2650     Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
2651                                                     CHECK_false);
2652     if (next == NULL)  break;
2653     if (next == class2())  return true;
2654     outer1 = instanceKlassHandle(THREAD, next);
2655   }
2656 
2657   // Now do the same for class2.
2658   instanceKlassHandle outer2 = class2;
2659   for (;;) {
2660     bool ignore_inner_is_member;
2661     Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
2662                                                     CHECK_false);
2663     if (next == NULL)  break;
2664     // Might as well check the new outer against all available values.
2665     if (next == class1())  return true;
2666     if (next == outer1())  return true;
2667     outer2 = instanceKlassHandle(THREAD, next);
2668   }
2669 
2670   // If by this point we have not found an equality between the
2671   // two classes, we know they are in separate package members.
2672   return false;
2673 }
2674 
2675 
2676 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
2677   jint access = access_flags().as_int();
2678 
2679   // But check if it happens to be member class.
2680   instanceKlassHandle ik(THREAD, this);
2681   InnerClassesIterator iter(ik);
2682   for (; !iter.done(); iter.next()) {
2683     int ioff = iter.inner_class_info_index();
2684     // Inner class attribute can be zero, skip it.
2685     // Strange but true:  JVM spec. allows null inner class refs.
2686     if (ioff == 0) continue;
2687 
2688     // only look at classes that are already loaded
2689     // since we are looking for the flags for our self.
2690     Symbol* inner_name = ik->constants()->klass_name_at(ioff);
2691     if ((ik->name() == inner_name)) {
2692       // This is really a member class.
2693       access = iter.inner_access_flags();
2694       break;
2695     }
2696   }
2697   // Remember to strip ACC_SUPER bit
2698   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
2699 }
2700 
2701 jint InstanceKlass::jvmti_class_status() const {
2702   jint result = 0;
2703 
2704   if (is_linked()) {
2705     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
2706   }
2707 
2708   if (is_initialized()) {
2709     assert(is_linked(), "Class status is not consistent");
2710     result |= JVMTI_CLASS_STATUS_INITIALIZED;
2711   }
2712   if (is_in_error_state()) {
2713     result |= JVMTI_CLASS_STATUS_ERROR;
2714   }
2715   return result;
2716 }
2717 
2718 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
2719   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2720   int method_table_offset_in_words = ioe->offset()/wordSize;
2721   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2722                        / itableOffsetEntry::size();
2723 
2724   for (int cnt = 0 ; ; cnt ++, ioe ++) {
2725     // If the interface isn't implemented by the receiver class,
2726     // the VM should throw IncompatibleClassChangeError.
2727     if (cnt >= nof_interfaces) {
2728       THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
2729     }
2730 
2731     Klass* ik = ioe->interface_klass();
2732     if (ik == holder) break;
2733   }
2734 
2735   itableMethodEntry* ime = ioe->first_method_entry(this);
2736   Method* m = ime[index].method();
2737   if (m == NULL) {
2738     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
2739   }
2740   return m;
2741 }
2742 
2743 
2744 #if INCLUDE_JVMTI
2745 // update default_methods for redefineclasses for methods that are
2746 // not yet in the vtable due to concurrent subclass define and superinterface
2747 // redefinition
2748 // Note: those in the vtable, should have been updated via adjust_method_entries
2749 void InstanceKlass::adjust_default_methods(Method** old_methods, Method** new_methods,
2750                                            int methods_length, bool* trace_name_printed) {
2751   // search the default_methods for uses of either obsolete or EMCP methods
2752   if (default_methods() != NULL) {
2753     for (int j = 0; j < methods_length; j++) {
2754       Method* old_method = old_methods[j];
2755       Method* new_method = new_methods[j];
2756 
2757       for (int index = 0; index < default_methods()->length(); index ++) {
2758         if (default_methods()->at(index) == old_method) {
2759           default_methods()->at_put(index, new_method);
2760           if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
2761             if (!(*trace_name_printed)) {
2762               // RC_TRACE_MESG macro has an embedded ResourceMark
2763               RC_TRACE_MESG(("adjust: klassname=%s default methods from name=%s",
2764                              external_name(),
2765                              old_method->method_holder()->external_name()));
2766               *trace_name_printed = true;
2767             }
2768             RC_TRACE(0x00100000, ("default method update: %s(%s) ",
2769                                   new_method->name()->as_C_string(),
2770                                   new_method->signature()->as_C_string()));
2771           }
2772         }
2773       }
2774     }
2775   }
2776 }
2777 #endif // INCLUDE_JVMTI
2778 
2779 // On-stack replacement stuff
2780 void InstanceKlass::add_osr_nmethod(nmethod* n) {
2781   // only one compilation can be active
2782   {
2783     // This is a short non-blocking critical region, so the no safepoint check is ok.
2784     MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
2785     assert(n->is_osr_method(), "wrong kind of nmethod");
2786     n->set_osr_link(osr_nmethods_head());
2787     set_osr_nmethods_head(n);
2788     // Raise the highest osr level if necessary
2789     if (TieredCompilation) {
2790       Method* m = n->method();
2791       m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
2792     }
2793   }
2794 
2795   // Get rid of the osr methods for the same bci that have lower levels.
2796   if (TieredCompilation) {
2797     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
2798       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
2799       if (inv != NULL && inv->is_in_use()) {
2800         inv->make_not_entrant();
2801       }
2802     }
2803   }
2804 }
2805 
2806 
2807 void InstanceKlass::remove_osr_nmethod(nmethod* n) {
2808   // This is a short non-blocking critical region, so the no safepoint check is ok.
2809   MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
2810   assert(n->is_osr_method(), "wrong kind of nmethod");
2811   nmethod* last = NULL;
2812   nmethod* cur  = osr_nmethods_head();
2813   int max_level = CompLevel_none;  // Find the max comp level excluding n
2814   Method* m = n->method();
2815   // Search for match
2816   while(cur != NULL && cur != n) {
2817     if (TieredCompilation && m == cur->method()) {
2818       // Find max level before n
2819       max_level = MAX2(max_level, cur->comp_level());
2820     }
2821     last = cur;
2822     cur = cur->osr_link();
2823   }
2824   nmethod* next = NULL;
2825   if (cur == n) {
2826     next = cur->osr_link();
2827     if (last == NULL) {
2828       // Remove first element
2829       set_osr_nmethods_head(next);
2830     } else {
2831       last->set_osr_link(next);
2832     }
2833   }
2834   n->set_osr_link(NULL);
2835   if (TieredCompilation) {
2836     cur = next;
2837     while (cur != NULL) {
2838       // Find max level after n
2839       if (m == cur->method()) {
2840         max_level = MAX2(max_level, cur->comp_level());
2841       }
2842       cur = cur->osr_link();
2843     }
2844     m->set_highest_osr_comp_level(max_level);
2845   }
2846 }
2847 
2848 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {

2849   // This is a short non-blocking critical region, so the no safepoint check is ok.
2850   MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
2851   nmethod* osr = osr_nmethods_head();
2852   nmethod* best = NULL;
2853   while (osr != NULL) {
2854     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
2855     // There can be a time when a c1 osr method exists but we are waiting
2856     // for a c2 version. When c2 completes its osr nmethod we will trash
2857     // the c1 version and only be able to find the c2 version. However
2858     // while we overflow in the c1 code at back branches we don't want to
2859     // try and switch to the same code as we are already running
2860 
2861     if (osr->method() == m &&
2862         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
2863       if (match_level) {
2864         if (osr->comp_level() == comp_level) {
2865           // Found a match - return it.
2866           return osr;
2867         }
2868       } else {
2869         if (best == NULL || (osr->comp_level() > best->comp_level())) {
2870           if (osr->comp_level() == CompLevel_highest_tier) {
2871             // Found the best possible - return it.
2872             return osr;
2873           }
2874           best = osr;
2875         }
2876       }
2877     }
2878     osr = osr->osr_link();
2879   }
2880   if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
2881     return best;
2882   }
2883   return NULL;
2884 }
2885 
2886 void InstanceKlass::add_member_name(int index, Handle mem_name) {
2887   jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);
2888   MutexLocker ml(MemberNameTable_lock);
2889   assert(0 <= index && index < idnum_allocated_count(), "index is out of bounds");
2890   DEBUG_ONLY(No_Safepoint_Verifier nsv);
2891 
2892   if (_member_names == NULL) {
2893     _member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count());
2894   }
2895   _member_names->add_member_name(index, mem_name_wref);
2896 }
2897 
2898 oop InstanceKlass::get_member_name(int index) {
2899   MutexLocker ml(MemberNameTable_lock);
2900   assert(0 <= index && index < idnum_allocated_count(), "index is out of bounds");
2901   DEBUG_ONLY(No_Safepoint_Verifier nsv);
2902 
2903   if (_member_names == NULL) {
2904     return NULL;
2905   }
2906   oop mem_name =_member_names->get_member_name(index);
2907   return mem_name;
2908 }
2909 
2910 // -----------------------------------------------------------------------------------------------------
2911 // Printing
2912 
2913 #ifndef PRODUCT
2914 
2915 #define BULLET  " - "
2916 
2917 static const char* state_names[] = {
2918   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
2919 };
2920 
2921 static void print_vtable(intptr_t* start, int len, outputStream* st) {
2922   for (int i = 0; i < len; i++) {
2923     intptr_t e = start[i];
2924     st->print("%d : " INTPTR_FORMAT, i, e);
2925     if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {
2926       st->print(" ");
2927       ((Metadata*)e)->print_value_on(st);
2928     }
2929     st->cr();
2930   }
2931 }
2932 
2933 void InstanceKlass::print_on(outputStream* st) const {
2934   assert(is_klass(), "must be klass");
2935   Klass::print_on(st);
2936 
2937   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
2938   st->print(BULLET"klass size:        %d", size());                               st->cr();
2939   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
2940   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
2941   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
2942   st->print(BULLET"super:             "); super()->print_value_on_maybe_null(st); st->cr();
2943   st->print(BULLET"sub:               ");
2944   Klass* sub = subklass();
2945   int n;
2946   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
2947     if (n < MaxSubklassPrintSize) {
2948       sub->print_value_on(st);
2949       st->print("   ");
2950     }
2951   }
2952   if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);
2953   st->cr();
2954 
2955   if (is_interface()) {
2956     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
2957     if (nof_implementors() == 1) {
2958       st->print_cr(BULLET"implementor:    ");
2959       st->print("   ");
2960       implementor()->print_value_on(st);
2961       st->cr();
2962     }
2963   }
2964 
2965   st->print(BULLET"arrays:            "); array_klasses()->print_value_on_maybe_null(st); st->cr();
2966   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
2967   if (Verbose || WizardMode) {
2968     Array<Method*>* method_array = methods();
2969     for (int i = 0; i < method_array->length(); i++) {
2970       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
2971     }
2972   }
2973   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
2974   st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
2975   if (Verbose && default_methods() != NULL) {
2976     Array<Method*>* method_array = default_methods();
2977     for (int i = 0; i < method_array->length(); i++) {
2978       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
2979     }
2980   }
2981   if (default_vtable_indices() != NULL) {
2982     st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
2983   }
2984   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
2985   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
2986   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
2987   if (class_loader_data() != NULL) {
2988     st->print(BULLET"class loader data:  ");
2989     class_loader_data()->print_value_on(st);
2990     st->cr();
2991   }
2992   st->print(BULLET"host class:        "); host_klass()->print_value_on_maybe_null(st); st->cr();
2993   if (source_file_name() != NULL) {
2994     st->print(BULLET"source file:       ");
2995     source_file_name()->print_value_on(st);
2996     st->cr();
2997   }
2998   if (source_debug_extension() != NULL) {
2999     st->print(BULLET"source debug extension:       ");
3000     st->print("%s", source_debug_extension());
3001     st->cr();
3002   }
3003   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
3004   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
3005   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
3006   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
3007   {
3008     bool have_pv = false;
3009     // previous versions are linked together through the InstanceKlass
3010     for (InstanceKlass* pv_node = _previous_versions;
3011          pv_node != NULL;
3012          pv_node = pv_node->previous_versions()) {
3013       if (!have_pv)
3014         st->print(BULLET"previous version:  ");
3015       have_pv = true;
3016       pv_node->constants()->print_value_on(st);
3017     }
3018     if (have_pv) st->cr();
3019   }
3020 
3021   if (generic_signature() != NULL) {
3022     st->print(BULLET"generic signature: ");
3023     generic_signature()->print_value_on(st);
3024     st->cr();
3025   }
3026   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
3027   st->print(BULLET"java mirror:       "); java_mirror()->print_value_on(st);       st->cr();
3028   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable());  st->cr();
3029   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
3030   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();
3031   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
3032   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3033   FieldPrinter print_static_field(st);
3034   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3035   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3036   FieldPrinter print_nonstatic_field(st);
3037   ((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);
3038 
3039   st->print(BULLET"non-static oop maps: ");
3040   OopMapBlock* map     = start_of_nonstatic_oop_maps();
3041   OopMapBlock* end_map = map + nonstatic_oop_map_count();
3042   while (map < end_map) {
3043     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3044     map++;
3045   }
3046   st->cr();
3047 }
3048 
3049 #endif //PRODUCT
3050 
3051 void InstanceKlass::print_value_on(outputStream* st) const {
3052   assert(is_klass(), "must be klass");
3053   if (Verbose || WizardMode)  access_flags().print_on(st);
3054   name()->print_value_on(st);
3055 }
3056 
3057 #ifndef PRODUCT
3058 
3059 void FieldPrinter::do_field(fieldDescriptor* fd) {
3060   _st->print(BULLET);
3061    if (_obj == NULL) {
3062      fd->print_on(_st);
3063      _st->cr();
3064    } else {
3065      fd->print_on_for(_st, _obj);
3066      _st->cr();
3067    }
3068 }
3069 
3070 
3071 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3072   Klass::oop_print_on(obj, st);
3073 
3074   if (this == SystemDictionary::String_klass()) {
3075     typeArrayOop value  = java_lang_String::value(obj);
3076     juint        offset = java_lang_String::offset(obj);
3077     juint        length = java_lang_String::length(obj);
3078     if (value != NULL &&
3079         value->is_typeArray() &&
3080         offset          <= (juint) value->length() &&
3081         offset + length <= (juint) value->length()) {
3082       st->print(BULLET"string: ");
3083       java_lang_String::print(obj, st);
3084       st->cr();
3085       if (!WizardMode)  return;  // that is enough
3086     }
3087   }
3088 
3089   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
3090   FieldPrinter print_field(st, obj);
3091   do_nonstatic_fields(&print_field);
3092 
3093   if (this == SystemDictionary::Class_klass()) {
3094     st->print(BULLET"signature: ");
3095     java_lang_Class::print_signature(obj, st);
3096     st->cr();
3097     Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
3098     st->print(BULLET"fake entry for mirror: ");
3099     mirrored_klass->print_value_on_maybe_null(st);
3100     st->cr();
3101     Klass* array_klass = java_lang_Class::array_klass(obj);
3102     st->print(BULLET"fake entry for array: ");
3103     array_klass->print_value_on_maybe_null(st);
3104     st->cr();
3105     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
3106     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
3107     Klass* real_klass = java_lang_Class::as_Klass(obj);
3108     if (real_klass != NULL && real_klass->oop_is_instance()) {
3109       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3110     }
3111   } else if (this == SystemDictionary::MethodType_klass()) {
3112     st->print(BULLET"signature: ");
3113     java_lang_invoke_MethodType::print_signature(obj, st);
3114     st->cr();
3115   }
3116 }
3117 
3118 #endif //PRODUCT
3119 
3120 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
3121   st->print("a ");
3122   name()->print_value_on(st);
3123   obj->print_address_on(st);
3124   if (this == SystemDictionary::String_klass()
3125       && java_lang_String::value(obj) != NULL) {
3126     ResourceMark rm;
3127     int len = java_lang_String::length(obj);
3128     int plen = (len < 24 ? len : 12);
3129     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
3130     st->print(" = \"%s\"", str);
3131     if (len > plen)
3132       st->print("...[%d]", len);
3133   } else if (this == SystemDictionary::Class_klass()) {
3134     Klass* k = java_lang_Class::as_Klass(obj);
3135     st->print(" = ");
3136     if (k != NULL) {
3137       k->print_value_on(st);
3138     } else {
3139       const char* tname = type2name(java_lang_Class::primitive_type(obj));
3140       st->print("%s", tname ? tname : "type?");
3141     }
3142   } else if (this == SystemDictionary::MethodType_klass()) {
3143     st->print(" = ");
3144     java_lang_invoke_MethodType::print_signature(obj, st);
3145   } else if (java_lang_boxing_object::is_instance(obj)) {
3146     st->print(" = ");
3147     java_lang_boxing_object::print(obj, st);
3148   } else if (this == SystemDictionary::LambdaForm_klass()) {
3149     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
3150     if (vmentry != NULL) {
3151       st->print(" => ");
3152       vmentry->print_value_on(st);
3153     }
3154   } else if (this == SystemDictionary::MemberName_klass()) {
3155     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
3156     if (vmtarget != NULL) {
3157       st->print(" = ");
3158       vmtarget->print_value_on(st);
3159     } else {
3160       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
3161       st->print(".");
3162       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
3163     }
3164   }
3165 }
3166 
3167 const char* InstanceKlass::internal_name() const {
3168   return external_name();
3169 }
3170 
3171 #if INCLUDE_SERVICES
3172 // Size Statistics
3173 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
3174   Klass::collect_statistics(sz);
3175 
3176   sz->_inst_size  = HeapWordSize * size_helper();
3177   sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());
3178   sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());
3179   sz->_nonstatic_oopmap_bytes = HeapWordSize *
3180         ((is_interface() || is_anonymous()) ?
3181          align_object_offset(nonstatic_oop_map_size()) :
3182          nonstatic_oop_map_size());
3183 
3184   int n = 0;
3185   n += (sz->_methods_array_bytes         = sz->count_array(methods()));
3186   n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
3187   n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
3188   n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
3189   n += (sz->_fields_bytes                = sz->count_array(fields()));
3190   n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
3191   sz->_ro_bytes += n;
3192 
3193   const ConstantPool* cp = constants();
3194   if (cp) {
3195     cp->collect_statistics(sz);
3196   }
3197 
3198   const Annotations* anno = annotations();
3199   if (anno) {
3200     anno->collect_statistics(sz);
3201   }
3202 
3203   const Array<Method*>* methods_array = methods();
3204   if (methods()) {
3205     for (int i = 0; i < methods_array->length(); i++) {
3206       Method* method = methods_array->at(i);
3207       if (method) {
3208         sz->_method_count ++;
3209         method->collect_statistics(sz);
3210       }
3211     }
3212   }
3213 }
3214 #endif // INCLUDE_SERVICES
3215 
3216 // Verification
3217 
3218 class VerifyFieldClosure: public OopClosure {
3219  protected:
3220   template <class T> void do_oop_work(T* p) {
3221     oop obj = oopDesc::load_decode_heap_oop(p);
3222     if (!obj->is_oop_or_null()) {
3223       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);
3224       Universe::print();
3225       guarantee(false, "boom");
3226     }
3227   }
3228  public:
3229   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
3230   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
3231 };
3232 
3233 void InstanceKlass::verify_on(outputStream* st) {
3234 #ifndef PRODUCT
3235   // Avoid redundant verifies, this really should be in product.
3236   if (_verify_count == Universe::verify_count()) return;
3237   _verify_count = Universe::verify_count();
3238 #endif
3239 
3240   // Verify Klass
3241   Klass::verify_on(st);
3242 
3243   // Verify that klass is present in ClassLoaderData
3244   guarantee(class_loader_data()->contains_klass(this),
3245             "this class isn't found in class loader data");
3246 
3247   // Verify vtables
3248   if (is_linked()) {
3249     ResourceMark rm;
3250     // $$$ This used to be done only for m/s collections.  Doing it
3251     // always seemed a valid generalization.  (DLD -- 6/00)
3252     vtable()->verify(st);
3253   }
3254 
3255   // Verify first subklass
3256   if (subklass() != NULL) {
3257     guarantee(subklass()->is_klass(), "should be klass");
3258   }
3259 
3260   // Verify siblings
3261   Klass* super = this->super();
3262   Klass* sib = next_sibling();
3263   if (sib != NULL) {
3264     if (sib == this) {
3265       fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));
3266     }
3267 
3268     guarantee(sib->is_klass(), "should be klass");
3269     guarantee(sib->super() == super, "siblings should have same superklass");
3270   }
3271 
3272   // Verify implementor fields
3273   Klass* im = implementor();
3274   if (im != NULL) {
3275     guarantee(is_interface(), "only interfaces should have implementor set");
3276     guarantee(im->is_klass(), "should be klass");
3277     guarantee(!im->is_interface() || im == this,
3278       "implementors cannot be interfaces");
3279   }
3280 
3281   // Verify local interfaces
3282   if (local_interfaces()) {
3283     Array<Klass*>* local_interfaces = this->local_interfaces();
3284     for (int j = 0; j < local_interfaces->length(); j++) {
3285       Klass* e = local_interfaces->at(j);
3286       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
3287     }
3288   }
3289 
3290   // Verify transitive interfaces
3291   if (transitive_interfaces() != NULL) {
3292     Array<Klass*>* transitive_interfaces = this->transitive_interfaces();
3293     for (int j = 0; j < transitive_interfaces->length(); j++) {
3294       Klass* e = transitive_interfaces->at(j);
3295       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
3296     }
3297   }
3298 
3299   // Verify methods
3300   if (methods() != NULL) {
3301     Array<Method*>* methods = this->methods();
3302     for (int j = 0; j < methods->length(); j++) {
3303       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3304     }
3305     for (int j = 0; j < methods->length() - 1; j++) {
3306       Method* m1 = methods->at(j);
3307       Method* m2 = methods->at(j + 1);
3308       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3309     }
3310   }
3311 
3312   // Verify method ordering
3313   if (method_ordering() != NULL) {
3314     Array<int>* method_ordering = this->method_ordering();
3315     int length = method_ordering->length();
3316     if (JvmtiExport::can_maintain_original_method_order() ||
3317         ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
3318       guarantee(length == methods()->length(), "invalid method ordering length");
3319       jlong sum = 0;
3320       for (int j = 0; j < length; j++) {
3321         int original_index = method_ordering->at(j);
3322         guarantee(original_index >= 0, "invalid method ordering index");
3323         guarantee(original_index < length, "invalid method ordering index");
3324         sum += original_index;
3325       }
3326       // Verify sum of indices 0,1,...,length-1
3327       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
3328     } else {
3329       guarantee(length == 0, "invalid method ordering length");
3330     }
3331   }
3332 
3333   // Verify default methods
3334   if (default_methods() != NULL) {
3335     Array<Method*>* methods = this->default_methods();
3336     for (int j = 0; j < methods->length(); j++) {
3337       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3338     }
3339     for (int j = 0; j < methods->length() - 1; j++) {
3340       Method* m1 = methods->at(j);
3341       Method* m2 = methods->at(j + 1);
3342       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3343     }
3344   }
3345 
3346   // Verify JNI static field identifiers
3347   if (jni_ids() != NULL) {
3348     jni_ids()->verify(this);
3349   }
3350 
3351   // Verify other fields
3352   if (array_klasses() != NULL) {
3353     guarantee(array_klasses()->is_klass(), "should be klass");
3354   }
3355   if (constants() != NULL) {
3356     guarantee(constants()->is_constantPool(), "should be constant pool");
3357   }
3358   const Klass* host = host_klass();
3359   if (host != NULL) {
3360     guarantee(host->is_klass(), "should be klass");
3361   }
3362 }
3363 
3364 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
3365   Klass::oop_verify_on(obj, st);
3366   VerifyFieldClosure blk;
3367   obj->oop_iterate_no_header(&blk);
3368 }
3369 
3370 
3371 // JNIid class for jfieldIDs only
3372 // Note to reviewers:
3373 // These JNI functions are just moved over to column 1 and not changed
3374 // in the compressed oops workspace.
3375 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
3376   _holder = holder;
3377   _offset = offset;
3378   _next = next;
3379   debug_only(_is_static_field_id = false;)
3380 }
3381 
3382 
3383 JNIid* JNIid::find(int offset) {
3384   JNIid* current = this;
3385   while (current != NULL) {
3386     if (current->offset() == offset) return current;
3387     current = current->next();
3388   }
3389   return NULL;
3390 }
3391 
3392 void JNIid::deallocate(JNIid* current) {
3393   while (current != NULL) {
3394     JNIid* next = current->next();
3395     delete current;
3396     current = next;
3397   }
3398 }
3399 
3400 
3401 void JNIid::verify(Klass* holder) {
3402   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
3403   int end_field_offset;
3404   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
3405 
3406   JNIid* current = this;
3407   while (current != NULL) {
3408     guarantee(current->holder() == holder, "Invalid klass in JNIid");
3409 #ifdef ASSERT
3410     int o = current->offset();
3411     if (current->is_static_field_id()) {
3412       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
3413     }
3414 #endif
3415     current = current->next();
3416   }
3417 }
3418 
3419 
3420 #ifdef ASSERT
3421 void InstanceKlass::set_init_state(ClassState state) {
3422   bool good_state = is_shared() ? (_init_state <= state)
3423                                                : (_init_state < state);
3424   assert(good_state || state == allocated, "illegal state transition");
3425   _init_state = (u1)state;
3426 }
3427 #endif
3428 
3429 
3430 // RedefineClasses() support for previous versions:
3431 
3432 // Purge previous versions
3433 void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
3434   if (ik->previous_versions() != NULL) {
3435     // This klass has previous versions so see what we can cleanup
3436     // while it is safe to do so.
3437 
3438     int deleted_count = 0;    // leave debugging breadcrumbs
3439     int live_count = 0;
3440     ClassLoaderData* loader_data = ik->class_loader_data();
3441     assert(loader_data != NULL, "should never be null");
3442 
3443     // RC_TRACE macro has an embedded ResourceMark
3444     RC_TRACE(0x00000200, ("purge: %s: previous versions", ik->external_name()));
3445 
3446     // previous versions are linked together through the InstanceKlass
3447     InstanceKlass* pv_node = ik->previous_versions();
3448     InstanceKlass* last = ik;
3449     int version = 0;
3450 
3451     // check the previous versions list
3452     for (; pv_node != NULL; ) {
3453 
3454       ConstantPool* pvcp = pv_node->constants();
3455       assert(pvcp != NULL, "cp ref was unexpectedly cleared");
3456 
3457       if (!pvcp->on_stack()) {
3458         // If the constant pool isn't on stack, none of the methods
3459         // are executing.  Unlink this previous_version.
3460         // The previous version InstanceKlass is on the ClassLoaderData deallocate list
3461         // so will be deallocated during the next phase of class unloading.
3462         pv_node = pv_node->previous_versions();
3463         last->link_previous_versions(pv_node);
3464         deleted_count++;
3465         version++;
3466         continue;
3467       } else {
3468         RC_TRACE(0x00000200, ("purge: previous version " INTPTR_FORMAT " is alive",
3469                               pv_node));
3470         assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
3471         guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
3472         live_count++;
3473       }
3474 
3475       // At least one method is live in this previous version so clean its MethodData.
3476       // Reset dead EMCP methods not to get breakpoints.
3477       // All methods are deallocated when all of the methods for this class are no
3478       // longer running.
3479       Array<Method*>* method_refs = pv_node->methods();
3480       if (method_refs != NULL) {
3481         RC_TRACE(0x00000200, ("purge: previous methods length=%d",
3482           method_refs->length()));
3483         for (int j = 0; j < method_refs->length(); j++) {
3484           Method* method = method_refs->at(j);
3485 
3486           if (!method->on_stack()) {
3487             // no breakpoints for non-running methods
3488             if (method->is_running_emcp()) {
3489               method->set_running_emcp(false);
3490             }
3491           } else {
3492             assert (method->is_obsolete() || method->is_running_emcp(),
3493                     "emcp method cannot run after emcp bit is cleared");
3494             // RC_TRACE macro has an embedded ResourceMark
3495             RC_TRACE(0x00000200,
3496               ("purge: %s(%s): prev method @%d in version @%d is alive",
3497               method->name()->as_C_string(),
3498               method->signature()->as_C_string(), j, version));
3499             if (method->method_data() != NULL) {
3500               // Clean out any weak method links for running methods
3501               // (also should include not EMCP methods)
3502               method->method_data()->clean_weak_method_links();
3503             }
3504           }
3505         }
3506       }
3507       // next previous version
3508       last = pv_node;
3509       pv_node = pv_node->previous_versions();
3510       version++;
3511     }
3512     RC_TRACE(0x00000200,
3513       ("purge: previous version stats: live=%d, deleted=%d", live_count,
3514       deleted_count));
3515   }
3516 
3517   // Clean MethodData of this class's methods so they don't refer to
3518   // old methods that are no longer running.
3519   Array<Method*>* methods = ik->methods();
3520   int num_methods = methods->length();
3521   for (int index2 = 0; index2 < num_methods; ++index2) {
3522     if (methods->at(index2)->method_data() != NULL) {
3523       methods->at(index2)->method_data()->clean_weak_method_links();
3524     }
3525   }
3526 }
3527 
3528 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,
3529                                                 int emcp_method_count) {
3530   int obsolete_method_count = old_methods->length() - emcp_method_count;
3531 
3532   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
3533       _previous_versions != NULL) {
3534     // We have a mix of obsolete and EMCP methods so we have to
3535     // clear out any matching EMCP method entries the hard way.
3536     int local_count = 0;
3537     for (int i = 0; i < old_methods->length(); i++) {
3538       Method* old_method = old_methods->at(i);
3539       if (old_method->is_obsolete()) {
3540         // only obsolete methods are interesting
3541         Symbol* m_name = old_method->name();
3542         Symbol* m_signature = old_method->signature();
3543 
3544         // previous versions are linked together through the InstanceKlass
3545         int j = 0;
3546         for (InstanceKlass* prev_version = _previous_versions;
3547              prev_version != NULL;
3548              prev_version = prev_version->previous_versions(), j++) {
3549 
3550           Array<Method*>* method_refs = prev_version->methods();
3551           for (int k = 0; k < method_refs->length(); k++) {
3552             Method* method = method_refs->at(k);
3553 
3554             if (!method->is_obsolete() &&
3555                 method->name() == m_name &&
3556                 method->signature() == m_signature) {
3557               // The current RedefineClasses() call has made all EMCP
3558               // versions of this method obsolete so mark it as obsolete
3559               RC_TRACE(0x00000400,
3560                 ("add: %s(%s): flush obsolete method @%d in version @%d",
3561                 m_name->as_C_string(), m_signature->as_C_string(), k, j));
3562 
3563               method->set_is_obsolete();
3564               break;
3565             }
3566           }
3567 
3568           // The previous loop may not find a matching EMCP method, but
3569           // that doesn't mean that we can optimize and not go any
3570           // further back in the PreviousVersion generations. The EMCP
3571           // method for this generation could have already been made obsolete,
3572           // but there still may be an older EMCP method that has not
3573           // been made obsolete.
3574         }
3575 
3576         if (++local_count >= obsolete_method_count) {
3577           // no more obsolete methods so bail out now
3578           break;
3579         }
3580       }
3581     }
3582   }
3583 }
3584 
3585 // Save the scratch_class as the previous version if any of the methods are running.
3586 // The previous_versions are used to set breakpoints in EMCP methods and they are
3587 // also used to clean MethodData links to redefined methods that are no longer running.
3588 void InstanceKlass::add_previous_version(instanceKlassHandle scratch_class,
3589                                          int emcp_method_count) {
3590   assert(Thread::current()->is_VM_thread(),
3591          "only VMThread can add previous versions");
3592 
3593   // RC_TRACE macro has an embedded ResourceMark
3594   RC_TRACE(0x00000400, ("adding previous version ref for %s, EMCP_cnt=%d",
3595     scratch_class->external_name(), emcp_method_count));
3596 
3597   // Clean out old previous versions
3598   purge_previous_versions(this);
3599 
3600   // Mark newly obsolete methods in remaining previous versions.  An EMCP method from
3601   // a previous redefinition may be made obsolete by this redefinition.
3602   Array<Method*>* old_methods = scratch_class->methods();
3603   mark_newly_obsolete_methods(old_methods, emcp_method_count);
3604 
3605   // If the constant pool for this previous version of the class
3606   // is not marked as being on the stack, then none of the methods
3607   // in this previous version of the class are on the stack so
3608   // we don't need to add this as a previous version.
3609   ConstantPool* cp_ref = scratch_class->constants();
3610   if (!cp_ref->on_stack()) {
3611     RC_TRACE(0x00000400, ("add: scratch class not added; no methods are running"));
3612     return;
3613   }
3614 
3615   if (emcp_method_count != 0) {
3616     // At least one method is still running, check for EMCP methods
3617     for (int i = 0; i < old_methods->length(); i++) {
3618       Method* old_method = old_methods->at(i);
3619       if (!old_method->is_obsolete() && old_method->on_stack()) {
3620         // if EMCP method (not obsolete) is on the stack, mark as EMCP so that
3621         // we can add breakpoints for it.
3622 
3623         // We set the method->on_stack bit during safepoints for class redefinition and
3624         // class unloading and use this bit to set the is_running_emcp bit.
3625         // After the safepoint, the on_stack bit is cleared and the running emcp
3626         // method may exit.   If so, we would set a breakpoint in a method that
3627         // is never reached, but this won't be noticeable to the programmer.
3628         old_method->set_running_emcp(true);
3629         RC_TRACE(0x00000400, ("add: EMCP method %s is on_stack " INTPTR_FORMAT,
3630                               old_method->name_and_sig_as_C_string(), old_method));
3631       } else if (!old_method->is_obsolete()) {
3632         RC_TRACE(0x00000400, ("add: EMCP method %s is NOT on_stack " INTPTR_FORMAT,
3633                               old_method->name_and_sig_as_C_string(), old_method));
3634       }
3635     }
3636   }
3637 
3638   // Add previous version if any methods are still running.
3639   RC_TRACE(0x00000400, ("add: scratch class added; one of its methods is on_stack"));
3640   assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");
3641   scratch_class->link_previous_versions(previous_versions());
3642   link_previous_versions(scratch_class());
3643 } // end add_previous_version()
3644 
3645 
3646 Method* InstanceKlass::method_with_idnum(int idnum) {
3647   Method* m = NULL;
3648   if (idnum < methods()->length()) {
3649     m = methods()->at(idnum);
3650   }
3651   if (m == NULL || m->method_idnum() != idnum) {
3652     for (int index = 0; index < methods()->length(); ++index) {
3653       m = methods()->at(index);
3654       if (m->method_idnum() == idnum) {
3655         return m;
3656       }
3657     }
3658     // None found, return null for the caller to handle.
3659     return NULL;
3660   }
3661   return m;
3662 }
3663 
3664 jint InstanceKlass::get_cached_class_file_len() {
3665   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
3666 }
3667 
3668 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
3669   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
3670 }
--- EOF ---