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