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