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