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