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