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