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