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