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