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