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