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