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