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