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