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