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