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