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