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 void restore_unshareable_in_class(Klass* k, TRAPS) {
2307   k->restore_unshareable_info(CHECK);
2308 }
2309 
2310 void InstanceKlass::restore_unshareable_info(TRAPS) {
2311   Klass::restore_unshareable_info(CHECK);
2312   instanceKlassHandle ik(THREAD, this);
2313 
2314   Array<Method*>* methods = ik->methods();
2315   int num_methods = methods->length();
2316   for (int index2 = 0; index2 < num_methods; ++index2) {
2317     methodHandle m(THREAD, methods->at(index2));
2318     m->restore_unshareable_info(CHECK);
2319   }
2320   if (JvmtiExport::has_redefined_a_class()) {
2321     // Reinitialize vtable because RedefineClasses may have changed some
2322     // entries in this vtable for super classes so the CDS vtable might
2323     // point to old or obsolete entries.  RedefineClasses doesn't fix up
2324     // vtables in the shared system dictionary, only the main one.
2325     // It also redefines the itable too so fix that too.
2326     ResourceMark rm(THREAD);
2327     ik->vtable()->initialize_vtable(false, CHECK);
2328     ik->itable()->initialize_itable(false, CHECK);
2329   }
2330 
2331   // restore constant pool resolved references
2332   ik->constants()->restore_unshareable_info(CHECK);
2333 
2334   ik->array_klasses_do(restore_unshareable_in_class, CHECK);
2335 }
2336 
2337 static void clear_all_breakpoints(Method* m) {
2338   m->clear_all_breakpoints();
2339 }
2340 
2341 
2342 void InstanceKlass::notify_unload_class(InstanceKlass* ik) {
2343   // notify the debugger
2344   if (JvmtiExport::should_post_class_unload()) {
2345     JvmtiExport::post_class_unload(ik);
2346   }
2347 
2348   // notify ClassLoadingService of class unload
2349   ClassLoadingService::notify_class_unloaded(ik);
2350 }
2351 
2352 void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {
2353   // Clean up C heap
2354   ik->release_C_heap_structures();
2355   ik->constants()->release_C_heap_structures();
2356 }
2357 
2358 void InstanceKlass::release_C_heap_structures() {
2359 
2360   // Can't release the constant pool here because the constant pool can be
2361   // deallocated separately from the InstanceKlass for default methods and
2362   // redefine classes.
2363 
2364   // Deallocate oop map cache
2365   if (_oop_map_cache != NULL) {
2366     delete _oop_map_cache;
2367     _oop_map_cache = NULL;
2368   }
2369 
2370   // Deallocate JNI identifiers for jfieldIDs
2371   JNIid::deallocate(jni_ids());
2372   set_jni_ids(NULL);
2373 
2374   jmethodID* jmeths = methods_jmethod_ids_acquire();
2375   if (jmeths != (jmethodID*)NULL) {
2376     release_set_methods_jmethod_ids(NULL);
2377     FreeHeap(jmeths);
2378   }
2379 
2380   // Deallocate MemberNameTable
2381   {
2382     Mutex* lock_or_null = SafepointSynchronize::is_at_safepoint() ? NULL : MemberNameTable_lock;
2383     MutexLockerEx ml(lock_or_null, Mutex::_no_safepoint_check_flag);
2384     MemberNameTable* mnt = member_names();
2385     if (mnt != NULL) {
2386       delete mnt;
2387       set_member_names(NULL);
2388     }
2389   }
2390 
2391   // release dependencies
2392   nmethodBucket* b = _dependencies;
2393   _dependencies = NULL;
2394   while (b != NULL) {
2395     nmethodBucket* next = b->next();
2396     delete b;
2397     b = next;
2398   }
2399 
2400   // Deallocate breakpoint records
2401   if (breakpoints() != 0x0) {
2402     methods_do(clear_all_breakpoints);
2403     assert(breakpoints() == 0x0, "should have cleared breakpoints");
2404   }
2405 
2406   // deallocate information about previous versions
2407   if (_previous_versions != NULL) {
2408     for (int i = _previous_versions->length() - 1; i >= 0; i--) {
2409       PreviousVersionNode * pv_node = _previous_versions->at(i);
2410       delete pv_node;
2411     }
2412     delete _previous_versions;
2413     _previous_versions = NULL;
2414   }
2415 
2416   // deallocate the cached class file
2417   if (_cached_class_file != NULL) {
2418     os::free(_cached_class_file, mtClass);
2419     _cached_class_file = NULL;
2420   }
2421 
2422   // Decrement symbol reference counts associated with the unloaded class.
2423   if (_name != NULL) _name->decrement_refcount();
2424   // unreference array name derived from this class name (arrays of an unloaded
2425   // class can't be referenced anymore).
2426   if (_array_name != NULL)  _array_name->decrement_refcount();
2427   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);
2428 
2429   assert(_total_instanceKlass_count >= 1, "Sanity check");
2430   Atomic::dec(&_total_instanceKlass_count);
2431 }
2432 
2433 void InstanceKlass::set_source_debug_extension(char* array, int length) {
2434   if (array == NULL) {
2435     _source_debug_extension = NULL;
2436   } else {
2437     // Adding one to the attribute length in order to store a null terminator
2438     // character could cause an overflow because the attribute length is
2439     // already coded with an u4 in the classfile, but in practice, it's
2440     // unlikely to happen.
2441     assert((length+1) > length, "Overflow checking");
2442     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2443     for (int i = 0; i < length; i++) {
2444       sde[i] = array[i];
2445     }
2446     sde[length] = '\0';
2447     _source_debug_extension = sde;
2448   }
2449 }
2450 
2451 address InstanceKlass::static_field_addr(int offset) {
2452   return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror()));
2453 }
2454 
2455 
2456 const char* InstanceKlass::signature_name() const {
2457   int hash_len = 0;
2458   char hash_buf[40];
2459 
2460   // If this is an anonymous class, append a hash to make the name unique
2461   if (is_anonymous()) {
2462     intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
2463     sprintf(hash_buf, "/" UINTX_FORMAT, (uintx)hash);
2464     hash_len = (int)strlen(hash_buf);
2465   }
2466 
2467   // Get the internal name as a c string
2468   const char* src = (const char*) (name()->as_C_string());
2469   const int src_length = (int)strlen(src);
2470 
2471   char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
2472 
2473   // Add L as type indicator
2474   int dest_index = 0;
2475   dest[dest_index++] = 'L';
2476 
2477   // Add the actual class name
2478   for (int src_index = 0; src_index < src_length; ) {
2479     dest[dest_index++] = src[src_index++];
2480   }
2481 
2482   // If we have a hash, append it
2483   for (int hash_index = 0; hash_index < hash_len; ) {
2484     dest[dest_index++] = hash_buf[hash_index++];
2485   }
2486 
2487   // Add the semicolon and the NULL
2488   dest[dest_index++] = ';';
2489   dest[dest_index] = '\0';
2490   return dest;
2491 }
2492 
2493 // different verisons of is_same_class_package
2494 bool InstanceKlass::is_same_class_package(Klass* class2) {
2495   Klass* class1 = this;
2496   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
2497   Symbol* classname1 = class1->name();
2498 
2499   if (class2->oop_is_objArray()) {
2500     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
2501   }
2502   oop classloader2;
2503   if (class2->oop_is_instance()) {
2504     classloader2 = InstanceKlass::cast(class2)->class_loader();
2505   } else {
2506     assert(class2->oop_is_typeArray(), "should be type array");
2507     classloader2 = NULL;
2508   }
2509   Symbol* classname2 = class2->name();
2510 
2511   return InstanceKlass::is_same_class_package(classloader1, classname1,
2512                                               classloader2, classname2);
2513 }
2514 
2515 bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
2516   Klass* class1 = this;
2517   oop classloader1 = InstanceKlass::cast(class1)->class_loader();
2518   Symbol* classname1 = class1->name();
2519 
2520   return InstanceKlass::is_same_class_package(classloader1, classname1,
2521                                               classloader2, classname2);
2522 }
2523 
2524 // return true if two classes are in the same package, classloader
2525 // and classname information is enough to determine a class's package
2526 bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
2527                                           oop class_loader2, Symbol* class_name2) {
2528   if (class_loader1 != class_loader2) {
2529     return false;
2530   } else if (class_name1 == class_name2) {
2531     return true;                // skip painful bytewise comparison
2532   } else {
2533     ResourceMark rm;
2534 
2535     // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly
2536     // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
2537     // Otherwise, we just compare jbyte values between the strings.
2538     const jbyte *name1 = class_name1->base();
2539     const jbyte *name2 = class_name2->base();
2540 
2541     const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
2542     const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
2543 
2544     if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
2545       // One of the two doesn't have a package.  Only return true
2546       // if the other one also doesn't have a package.
2547       return last_slash1 == last_slash2;
2548     } else {
2549       // Skip over '['s
2550       if (*name1 == '[') {
2551         do {
2552           name1++;
2553         } while (*name1 == '[');
2554         if (*name1 != 'L') {
2555           // Something is terribly wrong.  Shouldn't be here.
2556           return false;
2557         }
2558       }
2559       if (*name2 == '[') {
2560         do {
2561           name2++;
2562         } while (*name2 == '[');
2563         if (*name2 != 'L') {
2564           // Something is terribly wrong.  Shouldn't be here.
2565           return false;
2566         }
2567       }
2568 
2569       // Check that package part is identical
2570       int length1 = last_slash1 - name1;
2571       int length2 = last_slash2 - name2;
2572 
2573       return UTF8::equal(name1, length1, name2, length2);
2574     }
2575   }
2576 }
2577 
2578 // Returns true iff super_method can be overridden by a method in targetclassname
2579 // See JSL 3rd edition 8.4.6.1
2580 // Assumes name-signature match
2581 // "this" is InstanceKlass of super_method which must exist
2582 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
2583 bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
2584    // Private methods can not be overridden
2585    if (super_method->is_private()) {
2586      return false;
2587    }
2588    // If super method is accessible, then override
2589    if ((super_method->is_protected()) ||
2590        (super_method->is_public())) {
2591      return true;
2592    }
2593    // Package-private methods are not inherited outside of package
2594    assert(super_method->is_package_private(), "must be package private");
2595    return(is_same_class_package(targetclassloader(), targetclassname));
2596 }
2597 
2598 /* defined for now in jvm.cpp, for historical reasons *--
2599 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
2600                                                      Symbol*& simple_name_result, TRAPS) {
2601   ...
2602 }
2603 */
2604 
2605 // tell if two classes have the same enclosing class (at package level)
2606 bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
2607                                                 Klass* class2_oop, TRAPS) {
2608   if (class2_oop == class1())                       return true;
2609   if (!class2_oop->oop_is_instance())  return false;
2610   instanceKlassHandle class2(THREAD, class2_oop);
2611 
2612   // must be in same package before we try anything else
2613   if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
2614     return false;
2615 
2616   // As long as there is an outer1.getEnclosingClass,
2617   // shift the search outward.
2618   instanceKlassHandle outer1 = class1;
2619   for (;;) {
2620     // As we walk along, look for equalities between outer1 and class2.
2621     // Eventually, the walks will terminate as outer1 stops
2622     // at the top-level class around the original class.
2623     bool ignore_inner_is_member;
2624     Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
2625                                                     CHECK_false);
2626     if (next == NULL)  break;
2627     if (next == class2())  return true;
2628     outer1 = instanceKlassHandle(THREAD, next);
2629   }
2630 
2631   // Now do the same for class2.
2632   instanceKlassHandle outer2 = class2;
2633   for (;;) {
2634     bool ignore_inner_is_member;
2635     Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
2636                                                     CHECK_false);
2637     if (next == NULL)  break;
2638     // Might as well check the new outer against all available values.
2639     if (next == class1())  return true;
2640     if (next == outer1())  return true;
2641     outer2 = instanceKlassHandle(THREAD, next);
2642   }
2643 
2644   // If by this point we have not found an equality between the
2645   // two classes, we know they are in separate package members.
2646   return false;
2647 }
2648 
2649 
2650 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
2651   jint access = access_flags().as_int();
2652 
2653   // But check if it happens to be member class.
2654   instanceKlassHandle ik(THREAD, this);
2655   InnerClassesIterator iter(ik);
2656   for (; !iter.done(); iter.next()) {
2657     int ioff = iter.inner_class_info_index();
2658     // Inner class attribute can be zero, skip it.
2659     // Strange but true:  JVM spec. allows null inner class refs.
2660     if (ioff == 0) continue;
2661 
2662     // only look at classes that are already loaded
2663     // since we are looking for the flags for our self.
2664     Symbol* inner_name = ik->constants()->klass_name_at(ioff);
2665     if ((ik->name() == inner_name)) {
2666       // This is really a member class.
2667       access = iter.inner_access_flags();
2668       break;
2669     }
2670   }
2671   // Remember to strip ACC_SUPER bit
2672   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
2673 }
2674 
2675 jint InstanceKlass::jvmti_class_status() const {
2676   jint result = 0;
2677 
2678   if (is_linked()) {
2679     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
2680   }
2681 
2682   if (is_initialized()) {
2683     assert(is_linked(), "Class status is not consistent");
2684     result |= JVMTI_CLASS_STATUS_INITIALIZED;
2685   }
2686   if (is_in_error_state()) {
2687     result |= JVMTI_CLASS_STATUS_ERROR;
2688   }
2689   return result;
2690 }
2691 
2692 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
2693   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2694   int method_table_offset_in_words = ioe->offset()/wordSize;
2695   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2696                        / itableOffsetEntry::size();
2697 
2698   for (int cnt = 0 ; ; cnt ++, ioe ++) {
2699     // If the interface isn't implemented by the receiver class,
2700     // the VM should throw IncompatibleClassChangeError.
2701     if (cnt >= nof_interfaces) {
2702       THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
2703     }
2704 
2705     Klass* ik = ioe->interface_klass();
2706     if (ik == holder) break;
2707   }
2708 
2709   itableMethodEntry* ime = ioe->first_method_entry(this);
2710   Method* m = ime[index].method();
2711   if (m == NULL) {
2712     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
2713   }
2714   return m;
2715 }
2716 
2717 
2718 #if INCLUDE_JVMTI
2719 // update default_methods for redefineclasses for methods that are
2720 // not yet in the vtable due to concurrent subclass define and superinterface
2721 // redefinition
2722 // Note: those in the vtable, should have been updated via adjust_method_entries
2723 void InstanceKlass::adjust_default_methods(Method** old_methods, Method** new_methods,
2724                                            int methods_length, bool* trace_name_printed) {
2725   // search the default_methods for uses of either obsolete or EMCP methods
2726   if (default_methods() != NULL) {
2727     for (int j = 0; j < methods_length; j++) {
2728       Method* old_method = old_methods[j];
2729       Method* new_method = new_methods[j];
2730 
2731       for (int index = 0; index < default_methods()->length(); index ++) {
2732         if (default_methods()->at(index) == old_method) {
2733           default_methods()->at_put(index, new_method);
2734           if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
2735             if (!(*trace_name_printed)) {
2736               // RC_TRACE_MESG macro has an embedded ResourceMark
2737               RC_TRACE_MESG(("adjust: klassname=%s default methods from name=%s",
2738                              external_name(),
2739                              old_method->method_holder()->external_name()));
2740               *trace_name_printed = true;
2741             }
2742             RC_TRACE(0x00100000, ("default method update: %s(%s) ",
2743                                   new_method->name()->as_C_string(),
2744                                   new_method->signature()->as_C_string()));
2745           }
2746         }
2747       }
2748     }
2749   }
2750 }
2751 #endif // INCLUDE_JVMTI
2752 
2753 // On-stack replacement stuff
2754 void InstanceKlass::add_osr_nmethod(nmethod* n) {
2755   // only one compilation can be active
2756   NEEDS_CLEANUP
2757   // This is a short non-blocking critical region, so the no safepoint check is ok.
2758   OsrList_lock->lock_without_safepoint_check();
2759   assert(n->is_osr_method(), "wrong kind of nmethod");
2760   n->set_osr_link(osr_nmethods_head());
2761   set_osr_nmethods_head(n);
2762   // Raise the highest osr level if necessary
2763   if (TieredCompilation) {
2764     Method* m = n->method();
2765     m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
2766   }
2767   // Remember to unlock again
2768   OsrList_lock->unlock();
2769 
2770   // Get rid of the osr methods for the same bci that have lower levels.
2771   if (TieredCompilation) {
2772     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
2773       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
2774       if (inv != NULL && inv->is_in_use()) {
2775         inv->make_not_entrant();
2776       }
2777     }
2778   }
2779 }
2780 
2781 
2782 void InstanceKlass::remove_osr_nmethod(nmethod* n) {
2783   // This is a short non-blocking critical region, so the no safepoint check is ok.
2784   OsrList_lock->lock_without_safepoint_check();
2785   assert(n->is_osr_method(), "wrong kind of nmethod");
2786   nmethod* last = NULL;
2787   nmethod* cur  = osr_nmethods_head();
2788   int max_level = CompLevel_none;  // Find the max comp level excluding n
2789   Method* m = n->method();
2790   // Search for match
2791   while(cur != NULL && cur != n) {
2792     if (TieredCompilation && m == cur->method()) {
2793       // Find max level before n
2794       max_level = MAX2(max_level, cur->comp_level());
2795     }
2796     last = cur;
2797     cur = cur->osr_link();
2798   }
2799   nmethod* next = NULL;
2800   if (cur == n) {
2801     next = cur->osr_link();
2802     if (last == NULL) {
2803       // Remove first element
2804       set_osr_nmethods_head(next);
2805     } else {
2806       last->set_osr_link(next);
2807     }
2808   }
2809   n->set_osr_link(NULL);
2810   if (TieredCompilation) {
2811     cur = next;
2812     while (cur != NULL) {
2813       // Find max level after n
2814       if (m == cur->method()) {
2815         max_level = MAX2(max_level, cur->comp_level());
2816       }
2817       cur = cur->osr_link();
2818     }
2819     m->set_highest_osr_comp_level(max_level);
2820   }
2821   // Remember to unlock again
2822   OsrList_lock->unlock();
2823 }
2824 
2825 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
2826   // This is a short non-blocking critical region, so the no safepoint check is ok.
2827   OsrList_lock->lock_without_safepoint_check();
2828   nmethod* osr = osr_nmethods_head();
2829   nmethod* best = NULL;
2830   while (osr != NULL) {
2831     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
2832     // There can be a time when a c1 osr method exists but we are waiting
2833     // for a c2 version. When c2 completes its osr nmethod we will trash
2834     // the c1 version and only be able to find the c2 version. However
2835     // while we overflow in the c1 code at back branches we don't want to
2836     // try and switch to the same code as we are already running
2837 
2838     if (osr->method() == m &&
2839         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
2840       if (match_level) {
2841         if (osr->comp_level() == comp_level) {
2842           // Found a match - return it.
2843           OsrList_lock->unlock();
2844           return osr;
2845         }
2846       } else {
2847         if (best == NULL || (osr->comp_level() > best->comp_level())) {
2848           if (osr->comp_level() == CompLevel_highest_tier) {
2849             // Found the best possible - return it.
2850             OsrList_lock->unlock();
2851             return osr;
2852           }
2853           best = osr;
2854         }
2855       }
2856     }
2857     osr = osr->osr_link();
2858   }
2859   OsrList_lock->unlock();
2860   if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
2861     return best;
2862   }
2863   return NULL;
2864 }
2865 
2866 void InstanceKlass::add_member_name(int index, Handle mem_name) {
2867   jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);
2868   MutexLocker ml(MemberNameTable_lock);
2869   assert(0 <= index && index < idnum_allocated_count(), "index is out of bounds");
2870   DEBUG_ONLY(No_Safepoint_Verifier nsv);
2871 
2872   if (_member_names == NULL) {
2873     _member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count());
2874   }
2875   _member_names->add_member_name(index, mem_name_wref);
2876 }
2877 
2878 oop InstanceKlass::get_member_name(int index) {
2879   MutexLocker ml(MemberNameTable_lock);
2880   assert(0 <= index && index < idnum_allocated_count(), "index is out of bounds");
2881   DEBUG_ONLY(No_Safepoint_Verifier nsv);
2882 
2883   if (_member_names == NULL) {
2884     return NULL;
2885   }
2886   oop mem_name =_member_names->get_member_name(index);
2887   return mem_name;
2888 }
2889 
2890 // -----------------------------------------------------------------------------------------------------
2891 // Printing
2892 
2893 #ifndef PRODUCT
2894 
2895 #define BULLET  " - "
2896 
2897 static const char* state_names[] = {
2898   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
2899 };
2900 
2901 static void print_vtable(intptr_t* start, int len, outputStream* st) {
2902   for (int i = 0; i < len; i++) {
2903     intptr_t e = start[i];
2904     st->print("%d : " INTPTR_FORMAT, i, e);
2905     if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {
2906       st->print(" ");
2907       ((Metadata*)e)->print_value_on(st);
2908     }
2909     st->cr();
2910   }
2911 }
2912 
2913 void InstanceKlass::print_on(outputStream* st) const {
2914   assert(is_klass(), "must be klass");
2915   Klass::print_on(st);
2916 
2917   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
2918   st->print(BULLET"klass size:        %d", size());                               st->cr();
2919   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
2920   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
2921   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
2922   st->print(BULLET"super:             "); super()->print_value_on_maybe_null(st); st->cr();
2923   st->print(BULLET"sub:               ");
2924   Klass* sub = subklass();
2925   int n;
2926   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
2927     if (n < MaxSubklassPrintSize) {
2928       sub->print_value_on(st);
2929       st->print("   ");
2930     }
2931   }
2932   if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);
2933   st->cr();
2934 
2935   if (is_interface()) {
2936     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
2937     if (nof_implementors() == 1) {
2938       st->print_cr(BULLET"implementor:    ");
2939       st->print("   ");
2940       implementor()->print_value_on(st);
2941       st->cr();
2942     }
2943   }
2944 
2945   st->print(BULLET"arrays:            "); array_klasses()->print_value_on_maybe_null(st); st->cr();
2946   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
2947   if (Verbose || WizardMode) {
2948     Array<Method*>* method_array = methods();
2949     for (int i = 0; i < method_array->length(); i++) {
2950       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
2951     }
2952   }
2953   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
2954   st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
2955   if (Verbose && default_methods() != NULL) {
2956     Array<Method*>* method_array = default_methods();
2957     for (int i = 0; i < method_array->length(); i++) {
2958       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
2959     }
2960   }
2961   if (default_vtable_indices() != NULL) {
2962     st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
2963   }
2964   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
2965   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
2966   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
2967   if (class_loader_data() != NULL) {
2968     st->print(BULLET"class loader data:  ");
2969     class_loader_data()->print_value_on(st);
2970     st->cr();
2971   }
2972   st->print(BULLET"host class:        "); host_klass()->print_value_on_maybe_null(st); st->cr();
2973   if (source_file_name() != NULL) {
2974     st->print(BULLET"source file:       ");
2975     source_file_name()->print_value_on(st);
2976     st->cr();
2977   }
2978   if (source_debug_extension() != NULL) {
2979     st->print(BULLET"source debug extension:       ");
2980     st->print("%s", source_debug_extension());
2981     st->cr();
2982   }
2983   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
2984   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
2985   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
2986   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
2987   {
2988     bool have_pv = false;
2989     PreviousVersionWalker pvw(Thread::current(), (InstanceKlass*)this);
2990     for (PreviousVersionNode * pv_node = pvw.next_previous_version();
2991          pv_node != NULL; pv_node = pvw.next_previous_version()) {
2992       if (!have_pv)
2993         st->print(BULLET"previous version:  ");
2994       have_pv = true;
2995       pv_node->prev_constant_pool()->print_value_on(st);
2996     }
2997     if (have_pv) st->cr();
2998   } // pvw is cleaned up
2999 
3000   if (generic_signature() != NULL) {
3001     st->print(BULLET"generic signature: ");
3002     generic_signature()->print_value_on(st);
3003     st->cr();
3004   }
3005   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
3006   st->print(BULLET"java mirror:       "); java_mirror()->print_value_on(st);       st->cr();
3007   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable());  st->cr();
3008   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
3009   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();
3010   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
3011   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3012   FieldPrinter print_static_field(st);
3013   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3014   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3015   FieldPrinter print_nonstatic_field(st);
3016   ((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);
3017 
3018   st->print(BULLET"non-static oop maps: ");
3019   OopMapBlock* map     = start_of_nonstatic_oop_maps();
3020   OopMapBlock* end_map = map + nonstatic_oop_map_count();
3021   while (map < end_map) {
3022     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3023     map++;
3024   }
3025   st->cr();
3026 }
3027 
3028 #endif //PRODUCT
3029 
3030 void InstanceKlass::print_value_on(outputStream* st) const {
3031   assert(is_klass(), "must be klass");
3032   if (Verbose || WizardMode)  access_flags().print_on(st);
3033   name()->print_value_on(st);
3034 }
3035 
3036 #ifndef PRODUCT
3037 
3038 void FieldPrinter::do_field(fieldDescriptor* fd) {
3039   _st->print(BULLET);
3040    if (_obj == NULL) {
3041      fd->print_on(_st);
3042      _st->cr();
3043    } else {
3044      fd->print_on_for(_st, _obj);
3045      _st->cr();
3046    }
3047 }
3048 
3049 
3050 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3051   Klass::oop_print_on(obj, st);
3052 
3053   if (this == SystemDictionary::String_klass()) {
3054     typeArrayOop value  = java_lang_String::value(obj);
3055     juint        offset = java_lang_String::offset(obj);
3056     juint        length = java_lang_String::length(obj);
3057     if (value != NULL &&
3058         value->is_typeArray() &&
3059         offset          <= (juint) value->length() &&
3060         offset + length <= (juint) value->length()) {
3061       st->print(BULLET"string: ");
3062       java_lang_String::print(obj, st);
3063       st->cr();
3064       if (!WizardMode)  return;  // that is enough
3065     }
3066   }
3067 
3068   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
3069   FieldPrinter print_field(st, obj);
3070   do_nonstatic_fields(&print_field);
3071 
3072   if (this == SystemDictionary::Class_klass()) {
3073     st->print(BULLET"signature: ");
3074     java_lang_Class::print_signature(obj, st);
3075     st->cr();
3076     Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
3077     st->print(BULLET"fake entry for mirror: ");
3078     mirrored_klass->print_value_on_maybe_null(st);
3079     st->cr();
3080     Klass* array_klass = java_lang_Class::array_klass(obj);
3081     st->print(BULLET"fake entry for array: ");
3082     array_klass->print_value_on_maybe_null(st);
3083     st->cr();
3084     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
3085     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
3086     Klass* real_klass = java_lang_Class::as_Klass(obj);
3087     if (real_klass != NULL && real_klass->oop_is_instance()) {
3088       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3089     }
3090   } else if (this == SystemDictionary::MethodType_klass()) {
3091     st->print(BULLET"signature: ");
3092     java_lang_invoke_MethodType::print_signature(obj, st);
3093     st->cr();
3094   }
3095 }
3096 
3097 #endif //PRODUCT
3098 
3099 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
3100   st->print("a ");
3101   name()->print_value_on(st);
3102   obj->print_address_on(st);
3103   if (this == SystemDictionary::String_klass()
3104       && java_lang_String::value(obj) != NULL) {
3105     ResourceMark rm;
3106     int len = java_lang_String::length(obj);
3107     int plen = (len < 24 ? len : 12);
3108     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
3109     st->print(" = \"%s\"", str);
3110     if (len > plen)
3111       st->print("...[%d]", len);
3112   } else if (this == SystemDictionary::Class_klass()) {
3113     Klass* k = java_lang_Class::as_Klass(obj);
3114     st->print(" = ");
3115     if (k != NULL) {
3116       k->print_value_on(st);
3117     } else {
3118       const char* tname = type2name(java_lang_Class::primitive_type(obj));
3119       st->print("%s", tname ? tname : "type?");
3120     }
3121   } else if (this == SystemDictionary::MethodType_klass()) {
3122     st->print(" = ");
3123     java_lang_invoke_MethodType::print_signature(obj, st);
3124   } else if (java_lang_boxing_object::is_instance(obj)) {
3125     st->print(" = ");
3126     java_lang_boxing_object::print(obj, st);
3127   } else if (this == SystemDictionary::LambdaForm_klass()) {
3128     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
3129     if (vmentry != NULL) {
3130       st->print(" => ");
3131       vmentry->print_value_on(st);
3132     }
3133   } else if (this == SystemDictionary::MemberName_klass()) {
3134     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
3135     if (vmtarget != NULL) {
3136       st->print(" = ");
3137       vmtarget->print_value_on(st);
3138     } else {
3139       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
3140       st->print(".");
3141       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
3142     }
3143   }
3144 }
3145 
3146 const char* InstanceKlass::internal_name() const {
3147   return external_name();
3148 }
3149 
3150 #if INCLUDE_SERVICES
3151 // Size Statistics
3152 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
3153   Klass::collect_statistics(sz);
3154 
3155   sz->_inst_size  = HeapWordSize * size_helper();
3156   sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());
3157   sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());
3158   sz->_nonstatic_oopmap_bytes = HeapWordSize *
3159         ((is_interface() || is_anonymous()) ?
3160          align_object_offset(nonstatic_oop_map_size()) :
3161          nonstatic_oop_map_size());
3162 
3163   int n = 0;
3164   n += (sz->_methods_array_bytes         = sz->count_array(methods()));
3165   n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
3166   n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
3167   n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
3168   n += (sz->_fields_bytes                = sz->count_array(fields()));
3169   n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
3170   sz->_ro_bytes += n;
3171 
3172   const ConstantPool* cp = constants();
3173   if (cp) {
3174     cp->collect_statistics(sz);
3175   }
3176 
3177   const Annotations* anno = annotations();
3178   if (anno) {
3179     anno->collect_statistics(sz);
3180   }
3181 
3182   const Array<Method*>* methods_array = methods();
3183   if (methods()) {
3184     for (int i = 0; i < methods_array->length(); i++) {
3185       Method* method = methods_array->at(i);
3186       if (method) {
3187         sz->_method_count ++;
3188         method->collect_statistics(sz);
3189       }
3190     }
3191   }
3192 }
3193 #endif // INCLUDE_SERVICES
3194 
3195 // Verification
3196 
3197 class VerifyFieldClosure: public OopClosure {
3198  protected:
3199   template <class T> void do_oop_work(T* p) {
3200     oop obj = oopDesc::load_decode_heap_oop(p);
3201     if (!obj->is_oop_or_null()) {
3202       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);
3203       Universe::print();
3204       guarantee(false, "boom");
3205     }
3206   }
3207  public:
3208   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
3209   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
3210 };
3211 
3212 void InstanceKlass::verify_on(outputStream* st) {
3213 #ifndef PRODUCT
3214   // Avoid redundant verifies, this really should be in product.
3215   if (_verify_count == Universe::verify_count()) return;
3216   _verify_count = Universe::verify_count();
3217 #endif
3218 
3219   // Verify Klass
3220   Klass::verify_on(st);
3221 
3222   // Verify that klass is present in ClassLoaderData
3223   guarantee(class_loader_data()->contains_klass(this),
3224             "this class isn't found in class loader data");
3225 
3226   // Verify vtables
3227   if (is_linked()) {
3228     ResourceMark rm;
3229     // $$$ This used to be done only for m/s collections.  Doing it
3230     // always seemed a valid generalization.  (DLD -- 6/00)
3231     vtable()->verify(st);
3232   }
3233 
3234   // Verify first subklass
3235   if (subklass() != NULL) {
3236     guarantee(subklass()->is_klass(), "should be klass");
3237   }
3238 
3239   // Verify siblings
3240   Klass* super = this->super();
3241   Klass* sib = next_sibling();
3242   if (sib != NULL) {
3243     if (sib == this) {
3244       fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));
3245     }
3246 
3247     guarantee(sib->is_klass(), "should be klass");
3248     guarantee(sib->super() == super, "siblings should have same superklass");
3249   }
3250 
3251   // Verify implementor fields
3252   Klass* im = implementor();
3253   if (im != NULL) {
3254     guarantee(is_interface(), "only interfaces should have implementor set");
3255     guarantee(im->is_klass(), "should be klass");
3256     guarantee(!im->is_interface() || im == this,
3257       "implementors cannot be interfaces");
3258   }
3259 
3260   // Verify local interfaces
3261   if (local_interfaces()) {
3262     Array<Klass*>* local_interfaces = this->local_interfaces();
3263     for (int j = 0; j < local_interfaces->length(); j++) {
3264       Klass* e = local_interfaces->at(j);
3265       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
3266     }
3267   }
3268 
3269   // Verify transitive interfaces
3270   if (transitive_interfaces() != NULL) {
3271     Array<Klass*>* transitive_interfaces = this->transitive_interfaces();
3272     for (int j = 0; j < transitive_interfaces->length(); j++) {
3273       Klass* e = transitive_interfaces->at(j);
3274       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
3275     }
3276   }
3277 
3278   // Verify methods
3279   if (methods() != NULL) {
3280     Array<Method*>* methods = this->methods();
3281     for (int j = 0; j < methods->length(); j++) {
3282       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3283     }
3284     for (int j = 0; j < methods->length() - 1; j++) {
3285       Method* m1 = methods->at(j);
3286       Method* m2 = methods->at(j + 1);
3287       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3288     }
3289   }
3290 
3291   // Verify method ordering
3292   if (method_ordering() != NULL) {
3293     Array<int>* method_ordering = this->method_ordering();
3294     int length = method_ordering->length();
3295     if (JvmtiExport::can_maintain_original_method_order() ||
3296         ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
3297       guarantee(length == methods()->length(), "invalid method ordering length");
3298       jlong sum = 0;
3299       for (int j = 0; j < length; j++) {
3300         int original_index = method_ordering->at(j);
3301         guarantee(original_index >= 0, "invalid method ordering index");
3302         guarantee(original_index < length, "invalid method ordering index");
3303         sum += original_index;
3304       }
3305       // Verify sum of indices 0,1,...,length-1
3306       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
3307     } else {
3308       guarantee(length == 0, "invalid method ordering length");
3309     }
3310   }
3311 
3312   // Verify default methods
3313   if (default_methods() != NULL) {
3314     Array<Method*>* methods = this->default_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 JNI static field identifiers
3326   if (jni_ids() != NULL) {
3327     jni_ids()->verify(this);
3328   }
3329 
3330   // Verify other fields
3331   if (array_klasses() != NULL) {
3332     guarantee(array_klasses()->is_klass(), "should be klass");
3333   }
3334   if (constants() != NULL) {
3335     guarantee(constants()->is_constantPool(), "should be constant pool");
3336   }
3337   const Klass* host = host_klass();
3338   if (host != NULL) {
3339     guarantee(host->is_klass(), "should be klass");
3340   }
3341 }
3342 
3343 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
3344   Klass::oop_verify_on(obj, st);
3345   VerifyFieldClosure blk;
3346   obj->oop_iterate_no_header(&blk);
3347 }
3348 
3349 
3350 // JNIid class for jfieldIDs only
3351 // Note to reviewers:
3352 // These JNI functions are just moved over to column 1 and not changed
3353 // in the compressed oops workspace.
3354 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
3355   _holder = holder;
3356   _offset = offset;
3357   _next = next;
3358   debug_only(_is_static_field_id = false;)
3359 }
3360 
3361 
3362 JNIid* JNIid::find(int offset) {
3363   JNIid* current = this;
3364   while (current != NULL) {
3365     if (current->offset() == offset) return current;
3366     current = current->next();
3367   }
3368   return NULL;
3369 }
3370 
3371 void JNIid::deallocate(JNIid* current) {
3372   while (current != NULL) {
3373     JNIid* next = current->next();
3374     delete current;
3375     current = next;
3376   }
3377 }
3378 
3379 
3380 void JNIid::verify(Klass* holder) {
3381   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
3382   int end_field_offset;
3383   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
3384 
3385   JNIid* current = this;
3386   while (current != NULL) {
3387     guarantee(current->holder() == holder, "Invalid klass in JNIid");
3388 #ifdef ASSERT
3389     int o = current->offset();
3390     if (current->is_static_field_id()) {
3391       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
3392     }
3393 #endif
3394     current = current->next();
3395   }
3396 }
3397 
3398 
3399 #ifdef ASSERT
3400 void InstanceKlass::set_init_state(ClassState state) {
3401   bool good_state = is_shared() ? (_init_state <= state)
3402                                                : (_init_state < state);
3403   assert(good_state || state == allocated, "illegal state transition");
3404   _init_state = (u1)state;
3405 }
3406 #endif
3407 
3408 
3409 // RedefineClasses() support for previous versions:
3410 
3411 // Purge previous versions
3412 static void purge_previous_versions_internal(InstanceKlass* ik, int emcp_method_count) {
3413   if (ik->previous_versions() != NULL) {
3414     // This klass has previous versions so see what we can cleanup
3415     // while it is safe to do so.
3416 
3417     int deleted_count = 0;    // leave debugging breadcrumbs
3418     int live_count = 0;
3419     ClassLoaderData* loader_data = ik->class_loader_data() == NULL ?
3420                        ClassLoaderData::the_null_class_loader_data() :
3421                        ik->class_loader_data();
3422 
3423     // RC_TRACE macro has an embedded ResourceMark
3424     RC_TRACE(0x00000200, ("purge: %s: previous version length=%d",
3425       ik->external_name(), ik->previous_versions()->length()));
3426 
3427     for (int i = ik->previous_versions()->length() - 1; i >= 0; i--) {
3428       // check the previous versions array
3429       PreviousVersionNode * pv_node = ik->previous_versions()->at(i);
3430       ConstantPool* cp_ref = pv_node->prev_constant_pool();
3431       assert(cp_ref != NULL, "cp ref was unexpectedly cleared");
3432 
3433       ConstantPool* pvcp = cp_ref;
3434       if (!pvcp->on_stack()) {
3435         // If the constant pool isn't on stack, none of the methods
3436         // are executing.  Delete all the methods, the constant pool and
3437         // and this previous version node.
3438         GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
3439         if (method_refs != NULL) {
3440           for (int j = method_refs->length() - 1; j >= 0; j--) {
3441             Method* method = method_refs->at(j);
3442             assert(method != NULL, "method ref was unexpectedly cleared");
3443             method_refs->remove_at(j);
3444             // method will be freed with associated class.
3445           }
3446         }
3447         // Remove the constant pool
3448         delete pv_node;
3449         // Since we are traversing the array backwards, we don't have to
3450         // do anything special with the index.
3451         ik->previous_versions()->remove_at(i);
3452         deleted_count++;
3453         continue;
3454       } else {
3455         RC_TRACE(0x00000200, ("purge: previous version @%d is alive", i));
3456         assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
3457         guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
3458         live_count++;
3459       }
3460 
3461       // At least one method is live in this previous version, clean out
3462       // the others or mark them as obsolete.
3463       GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
3464       if (method_refs != NULL) {
3465         RC_TRACE(0x00000200, ("purge: previous methods length=%d",
3466           method_refs->length()));
3467         for (int j = method_refs->length() - 1; j >= 0; j--) {
3468           Method* method = method_refs->at(j);
3469           assert(method != NULL, "method ref was unexpectedly cleared");
3470 
3471           // Remove the emcp method if it's not executing
3472           // If it's been made obsolete by a redefinition of a non-emcp
3473           // method, mark it as obsolete but leave it to clean up later.
3474           if (!method->on_stack()) {
3475             method_refs->remove_at(j);
3476           } else if (emcp_method_count == 0) {
3477             method->set_is_obsolete();
3478           } else {
3479             // RC_TRACE macro has an embedded ResourceMark
3480             RC_TRACE(0x00000200,
3481               ("purge: %s(%s): prev method @%d in version @%d is alive",
3482               method->name()->as_C_string(),
3483               method->signature()->as_C_string(), j, i));
3484             if (method->method_data() != NULL) {
3485               // Clean out any weak method links
3486               method->method_data()->clean_weak_method_links();
3487             }
3488           }
3489         }
3490       }
3491     }
3492     assert(ik->previous_versions()->length() == live_count, "sanity check");
3493     RC_TRACE(0x00000200,
3494       ("purge: previous version stats: live=%d, deleted=%d", live_count,
3495       deleted_count));
3496   }
3497 
3498   Array<Method*>* methods = ik->methods();
3499   int num_methods = methods->length();
3500   for (int index2 = 0; index2 < num_methods; ++index2) {
3501     if (methods->at(index2)->method_data() != NULL) {
3502       methods->at(index2)->method_data()->clean_weak_method_links();
3503     }
3504   }
3505 }
3506 
3507 // External interface for use during class unloading.
3508 void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
3509   // Call with >0 emcp methods since they are not currently being redefined.
3510   purge_previous_versions_internal(ik, 1);
3511 }
3512 
3513 
3514 // Potentially add an information node that contains pointers to the
3515 // interesting parts of the previous version of the_class.
3516 // This is also where we clean out any unused references.
3517 // Note that while we delete nodes from the _previous_versions
3518 // array, we never delete the array itself until the klass is
3519 // unloaded. The has_been_redefined() query depends on that fact.
3520 //
3521 void InstanceKlass::add_previous_version(instanceKlassHandle ikh,
3522        BitMap* emcp_methods, int emcp_method_count) {
3523   assert(Thread::current()->is_VM_thread(),
3524          "only VMThread can add previous versions");
3525 
3526   if (_previous_versions == NULL) {
3527     // This is the first previous version so make some space.
3528     // Start with 2 elements under the assumption that the class
3529     // won't be redefined much.
3530     _previous_versions =  new (ResourceObj::C_HEAP, mtClass)
3531                             GrowableArray<PreviousVersionNode *>(2, true);
3532   }
3533 
3534   ConstantPool* cp_ref = ikh->constants();
3535 
3536   // RC_TRACE macro has an embedded ResourceMark
3537   RC_TRACE(0x00000400, ("adding previous version ref for %s @%d, EMCP_cnt=%d "
3538                         "on_stack=%d",
3539     ikh->external_name(), _previous_versions->length(), emcp_method_count,
3540     cp_ref->on_stack()));
3541 
3542   // If the constant pool for this previous version of the class
3543   // is not marked as being on the stack, then none of the methods
3544   // in this previous version of the class are on the stack so
3545   // we don't need to create a new PreviousVersionNode. However,
3546   // we still need to examine older previous versions below.
3547   Array<Method*>* old_methods = ikh->methods();
3548 
3549   if (cp_ref->on_stack()) {
3550     PreviousVersionNode * pv_node = NULL;
3551     if (emcp_method_count == 0) {
3552       // non-shared ConstantPool gets a reference
3553       pv_node = new PreviousVersionNode(cp_ref, NULL);
3554       RC_TRACE(0x00000400,
3555           ("add: all methods are obsolete; flushing any EMCP refs"));
3556     } else {
3557       int local_count = 0;
3558       GrowableArray<Method*>* method_refs = new (ResourceObj::C_HEAP, mtClass)
3559           GrowableArray<Method*>(emcp_method_count, true);
3560       for (int i = 0; i < old_methods->length(); i++) {
3561         if (emcp_methods->at(i)) {
3562             // this old method is EMCP. Save it only if it's on the stack
3563             Method* old_method = old_methods->at(i);
3564             if (old_method->on_stack()) {
3565               method_refs->append(old_method);
3566             }
3567           if (++local_count >= emcp_method_count) {
3568             // no more EMCP methods so bail out now
3569             break;
3570           }
3571         }
3572       }
3573       // non-shared ConstantPool gets a reference
3574       pv_node = new PreviousVersionNode(cp_ref, method_refs);
3575     }
3576     // append new previous version.
3577     _previous_versions->append(pv_node);
3578   }
3579 
3580   // Since the caller is the VMThread and we are at a safepoint, this
3581   // is a good time to clear out unused references.
3582 
3583   RC_TRACE(0x00000400, ("add: previous version length=%d",
3584     _previous_versions->length()));
3585 
3586   // Purge previous versions not executing on the stack
3587   purge_previous_versions_internal(this, emcp_method_count);
3588 
3589   int obsolete_method_count = old_methods->length() - emcp_method_count;
3590 
3591   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
3592       _previous_versions->length() > 0) {
3593     // We have a mix of obsolete and EMCP methods so we have to
3594     // clear out any matching EMCP method entries the hard way.
3595     int local_count = 0;
3596     for (int i = 0; i < old_methods->length(); i++) {
3597       if (!emcp_methods->at(i)) {
3598         // only obsolete methods are interesting
3599         Method* old_method = old_methods->at(i);
3600         Symbol* m_name = old_method->name();
3601         Symbol* m_signature = old_method->signature();
3602 
3603         // we might not have added the last entry
3604         for (int j = _previous_versions->length() - 1; j >= 0; j--) {
3605           // check the previous versions array for non executing obsolete methods
3606           PreviousVersionNode * pv_node = _previous_versions->at(j);
3607 
3608           GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
3609           if (method_refs == NULL) {
3610             // We have run into a PreviousVersion generation where
3611             // all methods were made obsolete during that generation's
3612             // RedefineClasses() operation. At the time of that
3613             // operation, all EMCP methods were flushed so we don't
3614             // have to go back any further.
3615             //
3616             // A NULL method_refs is different than an empty method_refs.
3617             // We cannot infer any optimizations about older generations
3618             // from an empty method_refs for the current generation.
3619             break;
3620           }
3621 
3622           for (int k = method_refs->length() - 1; k >= 0; k--) {
3623             Method* method = method_refs->at(k);
3624 
3625             if (!method->is_obsolete() &&
3626                 method->name() == m_name &&
3627                 method->signature() == m_signature) {
3628               // The current RedefineClasses() call has made all EMCP
3629               // versions of this method obsolete so mark it as obsolete
3630               // and remove the reference.
3631               RC_TRACE(0x00000400,
3632                 ("add: %s(%s): flush obsolete method @%d in version @%d",
3633                 m_name->as_C_string(), m_signature->as_C_string(), k, j));
3634 
3635               method->set_is_obsolete();
3636               // Leave obsolete methods on the previous version list to
3637               // clean up later.
3638               break;
3639             }
3640           }
3641 
3642           // The previous loop may not find a matching EMCP method, but
3643           // that doesn't mean that we can optimize and not go any
3644           // further back in the PreviousVersion generations. The EMCP
3645           // method for this generation could have already been deleted,
3646           // but there still may be an older EMCP method that has not
3647           // been deleted.
3648         }
3649 
3650         if (++local_count >= obsolete_method_count) {
3651           // no more obsolete methods so bail out now
3652           break;
3653         }
3654       }
3655     }
3656   }
3657 } // end add_previous_version()
3658 
3659 
3660 // Determine if InstanceKlass has a previous version.
3661 bool InstanceKlass::has_previous_version() const {
3662   return (_previous_versions != NULL && _previous_versions->length() > 0);
3663 } // end has_previous_version()
3664 
3665 
3666 Method* InstanceKlass::method_with_idnum(int idnum) {
3667   Method* m = NULL;
3668   if (idnum < methods()->length()) {
3669     m = methods()->at(idnum);
3670   }
3671   if (m == NULL || m->method_idnum() != idnum) {
3672     for (int index = 0; index < methods()->length(); ++index) {
3673       m = methods()->at(index);
3674       if (m->method_idnum() == idnum) {
3675         return m;
3676       }
3677     }
3678     // None found, return null for the caller to handle.
3679     return NULL;
3680   }
3681   return m;
3682 }
3683 
3684 jint InstanceKlass::get_cached_class_file_len() {
3685   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
3686 }
3687 
3688 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
3689   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
3690 }
3691 
3692 
3693 // Construct a PreviousVersionNode entry for the array hung off
3694 // the InstanceKlass.
3695 PreviousVersionNode::PreviousVersionNode(ConstantPool* prev_constant_pool,
3696   GrowableArray<Method*>* prev_EMCP_methods) {
3697 
3698   _prev_constant_pool = prev_constant_pool;
3699   _prev_EMCP_methods = prev_EMCP_methods;
3700 }
3701 
3702 
3703 // Destroy a PreviousVersionNode
3704 PreviousVersionNode::~PreviousVersionNode() {
3705   if (_prev_constant_pool != NULL) {
3706     _prev_constant_pool = NULL;
3707   }
3708 
3709   if (_prev_EMCP_methods != NULL) {
3710     delete _prev_EMCP_methods;
3711   }
3712 }
3713 
3714 // Construct a helper for walking the previous versions array
3715 PreviousVersionWalker::PreviousVersionWalker(Thread* thread, InstanceKlass *ik) {
3716   _thread = thread;
3717   _previous_versions = ik->previous_versions();
3718   _current_index = 0;
3719   _current_p = NULL;
3720   _current_constant_pool_handle = constantPoolHandle(thread, ik->constants());
3721 }
3722 
3723 
3724 // Return the interesting information for the next previous version
3725 // of the klass. Returns NULL if there are no more previous versions.
3726 PreviousVersionNode* PreviousVersionWalker::next_previous_version() {
3727   if (_previous_versions == NULL) {
3728     // no previous versions so nothing to return
3729     return NULL;
3730   }
3731 
3732   _current_p = NULL;  // reset to NULL
3733   _current_constant_pool_handle = NULL;
3734 
3735   int length = _previous_versions->length();
3736 
3737   while (_current_index < length) {
3738     PreviousVersionNode * pv_node = _previous_versions->at(_current_index++);
3739 
3740     // Save a handle to the constant pool for this previous version,
3741     // which keeps all the methods from being deallocated.
3742     _current_constant_pool_handle = constantPoolHandle(_thread, pv_node->prev_constant_pool());
3743     _current_p = pv_node;
3744     return pv_node;
3745   }
3746 
3747   return NULL;
3748 } // end next_previous_version()