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