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