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