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