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