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