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, find_overpass, find_static, find_private);
1773 }
1774 
1775 Method* InstanceKlass::find_method_impl(const Symbol* name,
1776                                         const Symbol* signature,
1777                                         OverpassLookupMode overpass_mode,
1778                                         StaticLookupMode static_mode,
1779                                         PrivateLookupMode private_mode) const {
1780   return InstanceKlass::find_method_impl(methods(),
1781                                          name,
1782                                          signature,
1783                                          overpass_mode,
1784                                          static_mode,
1785                                          private_mode);
1786 }
1787 
1788 // find_instance_method looks up the name/signature in the local methods array
1789 // and skips over static methods
1790 Method* InstanceKlass::find_instance_method(const Array<Method*>* methods,
1791                                             const Symbol* name,
1792                                             const Symbol* signature,
1793                                             PrivateLookupMode private_mode) {
1794   Method* const meth = InstanceKlass::find_method_impl(methods,
1795                                                  name,
1796                                                  signature,
1797                                                  find_overpass,
1798                                                  skip_static,
1799                                                  private_mode);
1800   assert(((meth == NULL) || !meth->is_static()),
1801     "find_instance_method should have skipped statics");
1802   return meth;
1803 }
1804 
1805 // find_instance_method looks up the name/signature in the local methods array
1806 // and skips over static methods
1807 Method* InstanceKlass::find_instance_method(const Symbol* name,
1808                                             const Symbol* signature,
1809                                             PrivateLookupMode private_mode) const {
1810   return InstanceKlass::find_instance_method(methods(), name, signature, private_mode);
1811 }
1812 
1813 // Find looks up the name/signature in the local methods array
1814 // and filters on the overpass, static and private flags
1815 // This returns the first one found
1816 // note that the local methods array can have up to one overpass, one static
1817 // and one instance (private or not) with the same name/signature
1818 Method* InstanceKlass::find_local_method(const Symbol* name,
1819                                          const Symbol* signature,
1820                                          OverpassLookupMode overpass_mode,
1821                                          StaticLookupMode static_mode,
1822                                          PrivateLookupMode private_mode) const {
1823   return InstanceKlass::find_method_impl(methods(),
1824                                          name,
1825                                          signature,
1826                                          overpass_mode,
1827                                          static_mode,
1828                                          private_mode);
1829 }
1830 
1831 // Find looks up the name/signature in the local methods array
1832 // and filters on the overpass, static and private flags
1833 // This returns the first one found
1834 // note that the local methods array can have up to one overpass, one static
1835 // and one instance (private or not) with the same name/signature
1836 Method* InstanceKlass::find_local_method(const Array<Method*>* methods,
1837                                          const Symbol* name,
1838                                          const Symbol* signature,
1839                                          OverpassLookupMode overpass_mode,
1840                                          StaticLookupMode static_mode,
1841                                          PrivateLookupMode private_mode) {
1842   return InstanceKlass::find_method_impl(methods,
1843                                          name,
1844                                          signature,
1845                                          overpass_mode,
1846                                          static_mode,
1847                                          private_mode);
1848 }
1849 
1850 Method* InstanceKlass::find_method(const Array<Method*>* methods,
1851                                    const Symbol* name,
1852                                    const Symbol* signature) {
1853   return InstanceKlass::find_method_impl(methods,
1854                                          name,
1855                                          signature,
1856                                          find_overpass,
1857                                          find_static,
1858                                          find_private);
1859 }
1860 
1861 Method* InstanceKlass::find_method_impl(const Array<Method*>* methods,
1862                                         const Symbol* name,
1863                                         const Symbol* signature,
1864                                         OverpassLookupMode overpass_mode,
1865                                         StaticLookupMode static_mode,
1866                                         PrivateLookupMode private_mode) {
1867   int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode);
1868   return hit >= 0 ? methods->at(hit): NULL;
1869 }
1870 
1871 // true if method matches signature and conforms to skipping_X conditions.
1872 static bool method_matches(const Method* m,
1873                            const Symbol* signature,
1874                            bool skipping_overpass,
1875                            bool skipping_static,
1876                            bool skipping_private) {
1877   return ((m->signature() == signature) &&
1878     (!skipping_overpass || !m->is_overpass()) &&
1879     (!skipping_static || !m->is_static()) &&
1880     (!skipping_private || !m->is_private()));
1881 }
1882 
1883 // Used directly for default_methods to find the index into the
1884 // default_vtable_indices, and indirectly by find_method
1885 // find_method_index looks in the local methods array to return the index
1886 // of the matching name/signature. If, overpass methods are being ignored,
1887 // the search continues to find a potential non-overpass match.  This capability
1888 // is important during method resolution to prefer a static method, for example,
1889 // over an overpass method.
1890 // There is the possibility in any _method's array to have the same name/signature
1891 // for a static method, an overpass method and a local instance method
1892 // To correctly catch a given method, the search criteria may need
1893 // to explicitly skip the other two. For local instance methods, it
1894 // is often necessary to skip private methods
1895 int InstanceKlass::find_method_index(const Array<Method*>* methods,
1896                                      const Symbol* name,
1897                                      const Symbol* signature,
1898                                      OverpassLookupMode overpass_mode,
1899                                      StaticLookupMode static_mode,
1900                                      PrivateLookupMode private_mode) {
1901   const bool skipping_overpass = (overpass_mode == skip_overpass);
1902   const bool skipping_static = (static_mode == skip_static);
1903   const bool skipping_private = (private_mode == skip_private);
1904   const int hit = quick_search(methods, name);
1905   if (hit != -1) {
1906     const Method* const m = methods->at(hit);
1907 
1908     // Do linear search to find matching signature.  First, quick check
1909     // for common case, ignoring overpasses if requested.
1910     if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1911       return hit;
1912     }
1913 
1914     // search downwards through overloaded methods
1915     int i;
1916     for (i = hit - 1; i >= 0; --i) {
1917         const Method* const m = methods->at(i);
1918         assert(m->is_method(), "must be method");
1919         if (m->name() != name) {
1920           break;
1921         }
1922         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1923           return i;
1924         }
1925     }
1926     // search upwards
1927     for (i = hit + 1; i < methods->length(); ++i) {
1928         const Method* const m = methods->at(i);
1929         assert(m->is_method(), "must be method");
1930         if (m->name() != name) {
1931           break;
1932         }
1933         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1934           return i;
1935         }
1936     }
1937     // not found
1938 #ifdef ASSERT
1939     const int index = (skipping_overpass || skipping_static || skipping_private) ? -1 :
1940       linear_search(methods, name, signature);
1941     assert(-1 == index, "binary search should have found entry %d", index);
1942 #endif
1943   }
1944   return -1;
1945 }
1946 
1947 int InstanceKlass::find_method_by_name(const Symbol* name, int* end) const {
1948   return find_method_by_name(methods(), name, end);
1949 }
1950 
1951 int InstanceKlass::find_method_by_name(const Array<Method*>* methods,
1952                                        const Symbol* name,
1953                                        int* end_ptr) {
1954   assert(end_ptr != NULL, "just checking");
1955   int start = quick_search(methods, name);
1956   int end = start + 1;
1957   if (start != -1) {
1958     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
1959     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
1960     *end_ptr = end;
1961     return start;
1962   }
1963   return -1;
1964 }
1965 
1966 // uncached_lookup_method searches both the local class methods array and all
1967 // superclasses methods arrays, skipping any overpass methods in superclasses,
1968 // and possibly skipping private methods.
1969 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
1970                                               const Symbol* signature,
1971                                               OverpassLookupMode overpass_mode,
1972                                               PrivateLookupMode private_mode) const {
1973   OverpassLookupMode overpass_local_mode = overpass_mode;
1974   const Klass* klass = this;
1975   while (klass != NULL) {
1976     Method* const method = InstanceKlass::cast(klass)->find_method_impl(name,
1977                                                                         signature,
1978                                                                         overpass_local_mode,
1979                                                                         find_static,
1980                                                                         private_mode);
1981     if (method != NULL) {
1982       return method;
1983     }
1984     klass = klass->super();
1985     overpass_local_mode = skip_overpass;   // Always ignore overpass methods in superclasses
1986   }
1987   return NULL;
1988 }
1989 
1990 #ifdef ASSERT
1991 // search through class hierarchy and return true if this class or
1992 // one of the superclasses was redefined
1993 bool InstanceKlass::has_redefined_this_or_super() const {
1994   const Klass* klass = this;
1995   while (klass != NULL) {
1996     if (InstanceKlass::cast(klass)->has_been_redefined()) {
1997       return true;
1998     }
1999     klass = klass->super();
2000   }
2001   return false;
2002 }
2003 #endif
2004 
2005 // lookup a method in the default methods list then in all transitive interfaces
2006 // Do NOT return private or static methods
2007 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
2008                                                          Symbol* signature) const {
2009   Method* m = NULL;
2010   if (default_methods() != NULL) {
2011     m = find_method(default_methods(), name, signature);
2012   }
2013   // Look up interfaces
2014   if (m == NULL) {
2015     m = lookup_method_in_all_interfaces(name, signature, find_defaults);
2016   }
2017   return m;
2018 }
2019 
2020 // lookup a method in all the interfaces that this class implements
2021 // Do NOT return private or static methods, new in JDK8 which are not externally visible
2022 // They should only be found in the initial InterfaceMethodRef
2023 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
2024                                                        Symbol* signature,
2025                                                        DefaultsLookupMode defaults_mode) const {
2026   Array<InstanceKlass*>* all_ifs = transitive_interfaces();
2027   int num_ifs = all_ifs->length();
2028   InstanceKlass *ik = NULL;
2029   for (int i = 0; i < num_ifs; i++) {
2030     ik = all_ifs->at(i);
2031     Method* m = ik->lookup_method(name, signature);
2032     if (m != NULL && m->is_public() && !m->is_static() &&
2033         ((defaults_mode != skip_defaults) || !m->is_default_method())) {
2034       return m;
2035     }
2036   }
2037   return NULL;
2038 }
2039 
2040 /* jni_id_for_impl for jfieldIds only */
2041 JNIid* InstanceKlass::jni_id_for_impl(int offset) {
2042   MutexLocker ml(JfieldIdCreation_lock);
2043   // Retry lookup after we got the lock
2044   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
2045   if (probe == NULL) {
2046     // Slow case, allocate new static field identifier
2047     probe = new JNIid(this, offset, jni_ids());
2048     set_jni_ids(probe);
2049   }
2050   return probe;
2051 }
2052 
2053 
2054 /* jni_id_for for jfieldIds only */
2055 JNIid* InstanceKlass::jni_id_for(int offset) {
2056   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
2057   if (probe == NULL) {
2058     probe = jni_id_for_impl(offset);
2059   }
2060   return probe;
2061 }
2062 
2063 u2 InstanceKlass::enclosing_method_data(int offset) const {
2064   const Array<jushort>* const inner_class_list = inner_classes();
2065   if (inner_class_list == NULL) {
2066     return 0;
2067   }
2068   const int length = inner_class_list->length();
2069   if (length % inner_class_next_offset == 0) {
2070     return 0;
2071   }
2072   const int index = length - enclosing_method_attribute_size;
2073   assert(offset < enclosing_method_attribute_size, "invalid offset");
2074   return inner_class_list->at(index + offset);
2075 }
2076 
2077 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
2078                                                  u2 method_index) {
2079   Array<jushort>* inner_class_list = inner_classes();
2080   assert (inner_class_list != NULL, "_inner_classes list is not set up");
2081   int length = inner_class_list->length();
2082   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
2083     int index = length - enclosing_method_attribute_size;
2084     inner_class_list->at_put(
2085       index + enclosing_method_class_index_offset, class_index);
2086     inner_class_list->at_put(
2087       index + enclosing_method_method_index_offset, method_index);
2088   }
2089 }
2090 
2091 // Lookup or create a jmethodID.
2092 // This code is called by the VMThread and JavaThreads so the
2093 // locking has to be done very carefully to avoid deadlocks
2094 // and/or other cache consistency problems.
2095 //
2096 jmethodID InstanceKlass::get_jmethod_id(const methodHandle& method_h) {
2097   size_t idnum = (size_t)method_h->method_idnum();
2098   jmethodID* jmeths = methods_jmethod_ids_acquire();
2099   size_t length = 0;
2100   jmethodID id = NULL;
2101 
2102   // We use a double-check locking idiom here because this cache is
2103   // performance sensitive. In the normal system, this cache only
2104   // transitions from NULL to non-NULL which is safe because we use
2105   // release_set_methods_jmethod_ids() to advertise the new cache.
2106   // A partially constructed cache should never be seen by a racing
2107   // thread. We also use release_store() to save a new jmethodID
2108   // in the cache so a partially constructed jmethodID should never be
2109   // seen either. Cache reads of existing jmethodIDs proceed without a
2110   // lock, but cache writes of a new jmethodID requires uniqueness and
2111   // creation of the cache itself requires no leaks so a lock is
2112   // generally acquired in those two cases.
2113   //
2114   // If the RedefineClasses() API has been used, then this cache can
2115   // grow and we'll have transitions from non-NULL to bigger non-NULL.
2116   // Cache creation requires no leaks and we require safety between all
2117   // cache accesses and freeing of the old cache so a lock is generally
2118   // acquired when the RedefineClasses() API has been used.
2119 
2120   if (jmeths != NULL) {
2121     // the cache already exists
2122     if (!idnum_can_increment()) {
2123       // the cache can't grow so we can just get the current values
2124       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
2125     } else {
2126       // cache can grow so we have to be more careful
2127       if (Threads::number_of_threads() == 0 ||
2128           SafepointSynchronize::is_at_safepoint()) {
2129         // we're single threaded or at a safepoint - no locking needed
2130         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
2131       } else {
2132         MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag);
2133         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
2134       }
2135     }
2136   }
2137   // implied else:
2138   // we need to allocate a cache so default length and id values are good
2139 
2140   if (jmeths == NULL ||   // no cache yet
2141       length <= idnum ||  // cache is too short
2142       id == NULL) {       // cache doesn't contain entry
2143 
2144     // This function can be called by the VMThread so we have to do all
2145     // things that might block on a safepoint before grabbing the lock.
2146     // Otherwise, we can deadlock with the VMThread or have a cache
2147     // consistency issue. These vars keep track of what we might have
2148     // to free after the lock is dropped.
2149     jmethodID  to_dealloc_id     = NULL;
2150     jmethodID* to_dealloc_jmeths = NULL;
2151 
2152     // may not allocate new_jmeths or use it if we allocate it
2153     jmethodID* new_jmeths = NULL;
2154     if (length <= idnum) {
2155       // allocate a new cache that might be used
2156       size_t size = MAX2(idnum+1, (size_t)idnum_allocated_count());
2157       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
2158       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
2159       // cache size is stored in element[0], other elements offset by one
2160       new_jmeths[0] = (jmethodID)size;
2161     }
2162 
2163     // allocate a new jmethodID that might be used
2164     jmethodID new_id = NULL;
2165     if (method_h->is_old() && !method_h->is_obsolete()) {
2166       // The method passed in is old (but not obsolete), we need to use the current version
2167       Method* current_method = method_with_idnum((int)idnum);
2168       assert(current_method != NULL, "old and but not obsolete, so should exist");
2169       new_id = Method::make_jmethod_id(class_loader_data(), current_method);
2170     } else {
2171       // It is the current version of the method or an obsolete method,
2172       // use the version passed in
2173       new_id = Method::make_jmethod_id(class_loader_data(), method_h());
2174     }
2175 
2176     if (Threads::number_of_threads() == 0 ||
2177         SafepointSynchronize::is_at_safepoint()) {
2178       // we're single threaded or at a safepoint - no locking needed
2179       id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,
2180                                           &to_dealloc_id, &to_dealloc_jmeths);
2181     } else {
2182       MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag);
2183       id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,
2184                                           &to_dealloc_id, &to_dealloc_jmeths);
2185     }
2186 
2187     // The lock has been dropped so we can free resources.
2188     // Free up either the old cache or the new cache if we allocated one.
2189     if (to_dealloc_jmeths != NULL) {
2190       FreeHeap(to_dealloc_jmeths);
2191     }
2192     // free up the new ID since it wasn't needed
2193     if (to_dealloc_id != NULL) {
2194       Method::destroy_jmethod_id(class_loader_data(), to_dealloc_id);
2195     }
2196   }
2197   return id;
2198 }
2199 
2200 // Figure out how many jmethodIDs haven't been allocated, and make
2201 // sure space for them is pre-allocated.  This makes getting all
2202 // method ids much, much faster with classes with more than 8
2203 // methods, and has a *substantial* effect on performance with jvmti
2204 // code that loads all jmethodIDs for all classes.
2205 void InstanceKlass::ensure_space_for_methodids(int start_offset) {
2206   int new_jmeths = 0;
2207   int length = methods()->length();
2208   for (int index = start_offset; index < length; index++) {
2209     Method* m = methods()->at(index);
2210     jmethodID id = m->find_jmethod_id_or_null();
2211     if (id == NULL) {
2212       new_jmeths++;
2213     }
2214   }
2215   if (new_jmeths != 0) {
2216     Method::ensure_jmethod_ids(class_loader_data(), new_jmeths);
2217   }
2218 }
2219 
2220 // Common code to fetch the jmethodID from the cache or update the
2221 // cache with the new jmethodID. This function should never do anything
2222 // that causes the caller to go to a safepoint or we can deadlock with
2223 // the VMThread or have cache consistency issues.
2224 //
2225 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
2226             size_t idnum, jmethodID new_id,
2227             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
2228             jmethodID** to_dealloc_jmeths_p) {
2229   assert(new_id != NULL, "sanity check");
2230   assert(to_dealloc_id_p != NULL, "sanity check");
2231   assert(to_dealloc_jmeths_p != NULL, "sanity check");
2232   assert(Threads::number_of_threads() == 0 ||
2233          SafepointSynchronize::is_at_safepoint() ||
2234          JmethodIdCreation_lock->owned_by_self(), "sanity check");
2235 
2236   // reacquire the cache - we are locked, single threaded or at a safepoint
2237   jmethodID* jmeths = methods_jmethod_ids_acquire();
2238   jmethodID  id     = NULL;
2239   size_t     length = 0;
2240 
2241   if (jmeths == NULL ||                         // no cache yet
2242       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
2243     if (jmeths != NULL) {
2244       // copy any existing entries from the old cache
2245       for (size_t index = 0; index < length; index++) {
2246         new_jmeths[index+1] = jmeths[index+1];
2247       }
2248       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
2249     }
2250     release_set_methods_jmethod_ids(jmeths = new_jmeths);
2251   } else {
2252     // fetch jmethodID (if any) from the existing cache
2253     id = jmeths[idnum+1];
2254     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
2255   }
2256   if (id == NULL) {
2257     // No matching jmethodID in the existing cache or we have a new
2258     // cache or we just grew the cache. This cache write is done here
2259     // by the first thread to win the foot race because a jmethodID
2260     // needs to be unique once it is generally available.
2261     id = new_id;
2262 
2263     // The jmethodID cache can be read while unlocked so we have to
2264     // make sure the new jmethodID is complete before installing it
2265     // in the cache.
2266     Atomic::release_store(&jmeths[idnum+1], id);
2267   } else {
2268     *to_dealloc_id_p = new_id; // save new id for later delete
2269   }
2270   return id;
2271 }
2272 
2273 
2274 // Common code to get the jmethodID cache length and the jmethodID
2275 // value at index idnum if there is one.
2276 //
2277 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
2278        size_t idnum, size_t *length_p, jmethodID* id_p) {
2279   assert(cache != NULL, "sanity check");
2280   assert(length_p != NULL, "sanity check");
2281   assert(id_p != NULL, "sanity check");
2282 
2283   // cache size is stored in element[0], other elements offset by one
2284   *length_p = (size_t)cache[0];
2285   if (*length_p <= idnum) {  // cache is too short
2286     *id_p = NULL;
2287   } else {
2288     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
2289   }
2290 }
2291 
2292 
2293 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
2294 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
2295   size_t idnum = (size_t)method->method_idnum();
2296   jmethodID* jmeths = methods_jmethod_ids_acquire();
2297   size_t length;                                // length assigned as debugging crumb
2298   jmethodID id = NULL;
2299   if (jmeths != NULL &&                         // If there is a cache
2300       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
2301     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
2302   }
2303   return id;
2304 }
2305 
2306 inline DependencyContext InstanceKlass::dependencies() {
2307   DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);
2308   return dep_context;
2309 }
2310 
2311 int InstanceKlass::mark_dependent_nmethods(KlassDepChange& changes) {
2312   return dependencies().mark_dependent_nmethods(changes);
2313 }
2314 
2315 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2316   dependencies().add_dependent_nmethod(nm);
2317 }
2318 
2319 void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
2320   dependencies().remove_dependent_nmethod(nm);
2321 }
2322 
2323 void InstanceKlass::clean_dependency_context() {
2324   dependencies().clean_unloading_dependents();
2325 }
2326 
2327 #ifndef PRODUCT
2328 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2329   dependencies().print_dependent_nmethods(verbose);
2330 }
2331 
2332 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2333   return dependencies().is_dependent_nmethod(nm);
2334 }
2335 #endif //PRODUCT
2336 
2337 void InstanceKlass::clean_weak_instanceklass_links() {
2338   clean_implementors_list();
2339   clean_method_data();
2340 }
2341 
2342 void InstanceKlass::clean_implementors_list() {
2343   assert(is_loader_alive(), "this klass should be live");
2344   if (is_interface()) {
2345     assert (ClassUnloading, "only called for ClassUnloading");
2346     for (;;) {
2347       // Use load_acquire due to competing with inserts
2348       Klass* impl = Atomic::load_acquire(adr_implementor());
2349       if (impl != NULL && !impl->is_loader_alive()) {
2350         // NULL this field, might be an unloaded klass or NULL
2351         Klass* volatile* klass = adr_implementor();
2352         if (Atomic::cmpxchg(klass, impl, (Klass*)NULL) == impl) {
2353           // Successfully unlinking implementor.
2354           if (log_is_enabled(Trace, class, unload)) {
2355             ResourceMark rm;
2356             log_trace(class, unload)("unlinking class (implementor): %s", impl->external_name());
2357           }
2358           return;
2359         }
2360       } else {
2361         return;
2362       }
2363     }
2364   }
2365 }
2366 
2367 void InstanceKlass::clean_method_data() {
2368   for (int m = 0; m < methods()->length(); m++) {
2369     MethodData* mdo = methods()->at(m)->method_data();
2370     if (mdo != NULL) {
2371       MutexLocker ml(SafepointSynchronize::is_at_safepoint() ? NULL : mdo->extra_data_lock());
2372       mdo->clean_method_data(/*always_clean*/false);
2373     }
2374   }
2375 }
2376 
2377 bool InstanceKlass::supers_have_passed_fingerprint_checks() {
2378   if (java_super() != NULL && !java_super()->has_passed_fingerprint_check()) {
2379     ResourceMark rm;
2380     log_trace(class, fingerprint)("%s : super %s not fingerprinted", external_name(), java_super()->external_name());
2381     return false;
2382   }
2383 
2384   Array<InstanceKlass*>* local_interfaces = this->local_interfaces();
2385   if (local_interfaces != NULL) {
2386     int length = local_interfaces->length();
2387     for (int i = 0; i < length; i++) {
2388       InstanceKlass* intf = local_interfaces->at(i);
2389       if (!intf->has_passed_fingerprint_check()) {
2390         ResourceMark rm;
2391         log_trace(class, fingerprint)("%s : interface %s not fingerprinted", external_name(), intf->external_name());
2392         return false;
2393       }
2394     }
2395   }
2396 
2397   return true;
2398 }
2399 
2400 bool InstanceKlass::should_store_fingerprint(bool is_hidden_or_anonymous) {
2401 #if INCLUDE_AOT
2402   // We store the fingerprint into the InstanceKlass only in the following 2 cases:
2403   if (CalculateClassFingerprint) {
2404     // (1) We are running AOT to generate a shared library.
2405     return true;
2406   }
2407   if (Arguments::is_dumping_archive()) {
2408     // (2) We are running -Xshare:dump or -XX:ArchiveClassesAtExit to create a shared archive
2409     return true;
2410   }
2411   if (UseAOT && is_hidden_or_anonymous) {
2412     // (3) We are using AOT code from a shared library and see a hidden or unsafe anonymous class
2413     return true;
2414   }
2415 #endif
2416 
2417   // In all other cases we might set the _misc_has_passed_fingerprint_check bit,
2418   // but do not store the 64-bit fingerprint to save space.
2419   return false;
2420 }
2421 
2422 bool InstanceKlass::has_stored_fingerprint() const {
2423 #if INCLUDE_AOT
2424   return should_store_fingerprint() || is_shared();
2425 #else
2426   return false;
2427 #endif
2428 }
2429 
2430 uint64_t InstanceKlass::get_stored_fingerprint() const {
2431   address adr = adr_fingerprint();
2432   if (adr != NULL) {
2433     return (uint64_t)Bytes::get_native_u8(adr); // adr may not be 64-bit aligned
2434   }
2435   return 0;
2436 }
2437 
2438 void InstanceKlass::store_fingerprint(uint64_t fingerprint) {
2439   address adr = adr_fingerprint();
2440   if (adr != NULL) {
2441     Bytes::put_native_u8(adr, (u8)fingerprint); // adr may not be 64-bit aligned
2442 
2443     ResourceMark rm;
2444     log_trace(class, fingerprint)("stored as " PTR64_FORMAT " for class %s", fingerprint, external_name());
2445   }
2446 }
2447 
2448 void InstanceKlass::metaspace_pointers_do(MetaspaceClosure* it) {
2449   Klass::metaspace_pointers_do(it);
2450 
2451   if (log_is_enabled(Trace, cds)) {
2452     ResourceMark rm;
2453     log_trace(cds)("Iter(InstanceKlass): %p (%s)", this, external_name());
2454   }
2455 
2456   it->push(&_annotations);
2457   it->push((Klass**)&_array_klasses);
2458   it->push(&_constants);
2459   it->push(&_inner_classes);
2460 #if INCLUDE_JVMTI
2461   it->push(&_previous_versions);
2462 #endif
2463   it->push(&_methods);
2464   it->push(&_default_methods);
2465   it->push(&_local_interfaces);
2466   it->push(&_transitive_interfaces);
2467   it->push(&_method_ordering);
2468   it->push(&_default_vtable_indices);
2469   it->push(&_fields);
2470 
2471   if (itable_length() > 0) {
2472     itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2473     int method_table_offset_in_words = ioe->offset()/wordSize;
2474     int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2475                          / itableOffsetEntry::size();
2476 
2477     for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2478       if (ioe->interface_klass() != NULL) {
2479         it->push(ioe->interface_klass_addr());
2480         itableMethodEntry* ime = ioe->first_method_entry(this);
2481         int n = klassItable::method_count_for_interface(ioe->interface_klass());
2482         for (int index = 0; index < n; index ++) {
2483           it->push(ime[index].method_addr());
2484         }
2485       }
2486     }
2487   }
2488 
2489   it->push(&_nest_members);
2490   it->push(&_permitted_subclasses);
2491   it->push(&_record_components);
2492 }
2493 
2494 void InstanceKlass::remove_unshareable_info() {
2495   Klass::remove_unshareable_info();
2496 
2497   if (SystemDictionaryShared::has_class_failed_verification(this)) {
2498     // Classes are attempted to link during dumping and may fail,
2499     // but these classes are still in the dictionary and class list in CLD.
2500     // If the class has failed verification, there is nothing else to remove.
2501     return;
2502   }
2503 
2504   // Reset to the 'allocated' state to prevent any premature accessing to
2505   // a shared class at runtime while the class is still being loaded and
2506   // restored. A class' init_state is set to 'loaded' at runtime when it's
2507   // being added to class hierarchy (see SystemDictionary:::add_to_hierarchy()).
2508   _init_state = allocated;
2509 
2510   { // Otherwise this needs to take out the Compile_lock.
2511     assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2512     init_implementor();
2513   }
2514 
2515   constants()->remove_unshareable_info();
2516 
2517   for (int i = 0; i < methods()->length(); i++) {
2518     Method* m = methods()->at(i);
2519     m->remove_unshareable_info();
2520   }
2521 
2522   // do array classes also.
2523   if (array_klasses() != NULL) {
2524     array_klasses()->remove_unshareable_info();
2525   }
2526 
2527   // These are not allocated from metaspace. They are safe to set to NULL.
2528   _source_debug_extension = NULL;
2529   _dep_context = NULL;
2530   _osr_nmethods_head = NULL;
2531 #if INCLUDE_JVMTI
2532   _breakpoints = NULL;
2533   _previous_versions = NULL;
2534   _cached_class_file = NULL;
2535   _jvmti_cached_class_field_map = NULL;
2536 #endif
2537 
2538   _init_thread = NULL;
2539   _methods_jmethod_ids = NULL;
2540   _jni_ids = NULL;
2541   _oop_map_cache = NULL;
2542   // clear _nest_host to ensure re-load at runtime
2543   _nest_host = NULL;
2544   _package_entry = NULL;
2545   _dep_context_last_cleaned = 0;
2546 }
2547 
2548 void InstanceKlass::remove_java_mirror() {
2549   Klass::remove_java_mirror();
2550 
2551   // do array classes also.
2552   if (array_klasses() != NULL) {
2553     array_klasses()->remove_java_mirror();
2554   }
2555 }
2556 
2557 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
2558                                              PackageEntry* pkg_entry, TRAPS) {
2559   // SystemDictionary::add_to_hierarchy() sets the init_state to loaded
2560   // before the InstanceKlass is added to the SystemDictionary. Make
2561   // sure the current state is <loaded.
2562   assert(!is_loaded(), "invalid init state");
2563   set_package(loader_data, pkg_entry, CHECK);
2564   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2565 
2566   Array<Method*>* methods = this->methods();
2567   int num_methods = methods->length();
2568   for (int index = 0; index < num_methods; ++index) {
2569     methods->at(index)->restore_unshareable_info(CHECK);
2570   }
2571   if (JvmtiExport::has_redefined_a_class()) {
2572     // Reinitialize vtable because RedefineClasses may have changed some
2573     // entries in this vtable for super classes so the CDS vtable might
2574     // point to old or obsolete entries.  RedefineClasses doesn't fix up
2575     // vtables in the shared system dictionary, only the main one.
2576     // It also redefines the itable too so fix that too.
2577     vtable().initialize_vtable(false, CHECK);
2578     itable().initialize_itable(false, CHECK);
2579   }
2580 
2581   // restore constant pool resolved references
2582   constants()->restore_unshareable_info(CHECK);
2583 
2584   if (array_klasses() != NULL) {
2585     // Array classes have null protection domain.
2586     // --> see ArrayKlass::complete_create_array_klass()
2587     array_klasses()->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);
2588   }
2589 
2590   // Initialize current biased locking state.
2591   if (UseBiasedLocking && BiasedLocking::enabled()) {
2592     set_prototype_header(markWord::biased_locking_prototype());
2593   }
2594 }
2595 
2596 void InstanceKlass::set_shared_class_loader_type(s2 loader_type) {
2597   switch (loader_type) {
2598   case ClassLoader::BOOT_LOADER:
2599     _misc_flags |= _misc_is_shared_boot_class;
2600     break;
2601   case ClassLoader::PLATFORM_LOADER:
2602     _misc_flags |= _misc_is_shared_platform_class;
2603     break;
2604   case ClassLoader::APP_LOADER:
2605     _misc_flags |= _misc_is_shared_app_class;
2606     break;
2607   default:
2608     ShouldNotReachHere();
2609     break;
2610   }
2611 }
2612 
2613 void InstanceKlass::assign_class_loader_type() {
2614   ClassLoaderData *cld = class_loader_data();
2615   if (cld->is_boot_class_loader_data()) {
2616     set_shared_class_loader_type(ClassLoader::BOOT_LOADER);
2617   }
2618   else if (cld->is_platform_class_loader_data()) {
2619     set_shared_class_loader_type(ClassLoader::PLATFORM_LOADER);
2620   }
2621   else if (cld->is_system_class_loader_data()) {
2622     set_shared_class_loader_type(ClassLoader::APP_LOADER);
2623   }
2624 }
2625 
2626 #if INCLUDE_JVMTI
2627 static void clear_all_breakpoints(Method* m) {
2628   m->clear_all_breakpoints();
2629 }
2630 #endif
2631 
2632 void InstanceKlass::unload_class(InstanceKlass* ik) {
2633   // Release dependencies.
2634   ik->dependencies().remove_all_dependents();
2635 
2636   // notify the debugger
2637   if (JvmtiExport::should_post_class_unload()) {
2638     JvmtiExport::post_class_unload(ik);
2639   }
2640 
2641   // notify ClassLoadingService of class unload
2642   ClassLoadingService::notify_class_unloaded(ik);
2643 
2644   if (Arguments::is_dumping_archive()) {
2645     SystemDictionaryShared::remove_dumptime_info(ik);
2646   }
2647 
2648   if (log_is_enabled(Info, class, unload)) {
2649     ResourceMark rm;
2650     log_info(class, unload)("unloading class %s " INTPTR_FORMAT, ik->external_name(), p2i(ik));
2651   }
2652 
2653   Events::log_class_unloading(Thread::current(), ik);
2654 
2655 #if INCLUDE_JFR
2656   assert(ik != NULL, "invariant");
2657   EventClassUnload event;
2658   event.set_unloadedClass(ik);
2659   event.set_definingClassLoader(ik->class_loader_data());
2660   event.commit();
2661 #endif
2662 }
2663 
2664 static void method_release_C_heap_structures(Method* m) {
2665   m->release_C_heap_structures();
2666 }
2667 
2668 void InstanceKlass::release_C_heap_structures() {
2669 
2670   // Clean up C heap
2671   release_C_heap_structures_internal();
2672   constants()->release_C_heap_structures();
2673 
2674   // Deallocate and call destructors for MDO mutexes
2675   methods_do(method_release_C_heap_structures);
2676 }
2677 
2678 void InstanceKlass::release_C_heap_structures_internal() {
2679   Klass::release_C_heap_structures();
2680 
2681   // Can't release the constant pool here because the constant pool can be
2682   // deallocated separately from the InstanceKlass for default methods and
2683   // redefine classes.
2684 
2685   // Deallocate oop map cache
2686   if (_oop_map_cache != NULL) {
2687     delete _oop_map_cache;
2688     _oop_map_cache = NULL;
2689   }
2690 
2691   // Deallocate JNI identifiers for jfieldIDs
2692   JNIid::deallocate(jni_ids());
2693   set_jni_ids(NULL);
2694 
2695   jmethodID* jmeths = methods_jmethod_ids_acquire();
2696   if (jmeths != (jmethodID*)NULL) {
2697     release_set_methods_jmethod_ids(NULL);
2698     FreeHeap(jmeths);
2699   }
2700 
2701   assert(_dep_context == NULL,
2702          "dependencies should already be cleaned");
2703 
2704 #if INCLUDE_JVMTI
2705   // Deallocate breakpoint records
2706   if (breakpoints() != 0x0) {
2707     methods_do(clear_all_breakpoints);
2708     assert(breakpoints() == 0x0, "should have cleared breakpoints");
2709   }
2710 
2711   // deallocate the cached class file
2712   if (_cached_class_file != NULL) {
2713     os::free(_cached_class_file);
2714     _cached_class_file = NULL;
2715   }
2716 #endif
2717 
2718   FREE_C_HEAP_ARRAY(char, _source_debug_extension);
2719 }
2720 
2721 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
2722   if (array == NULL) {
2723     _source_debug_extension = NULL;
2724   } else {
2725     // Adding one to the attribute length in order to store a null terminator
2726     // character could cause an overflow because the attribute length is
2727     // already coded with an u4 in the classfile, but in practice, it's
2728     // unlikely to happen.
2729     assert((length+1) > length, "Overflow checking");
2730     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2731     for (int i = 0; i < length; i++) {
2732       sde[i] = array[i];
2733     }
2734     sde[length] = '\0';
2735     _source_debug_extension = sde;
2736   }
2737 }
2738 
2739 const char* InstanceKlass::signature_name() const {
2740   int hash_len = 0;
2741   char hash_buf[40];
2742 
2743   // If this is an unsafe anonymous class, append a hash to make the name unique
2744   if (is_unsafe_anonymous()) {
2745     intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
2746     jio_snprintf(hash_buf, sizeof(hash_buf), "/" UINTX_FORMAT, (uintx)hash);
2747     hash_len = (int)strlen(hash_buf);
2748   }
2749 
2750   // Get the internal name as a c string
2751   const char* src = (const char*) (name()->as_C_string());
2752   const int src_length = (int)strlen(src);
2753 
2754   char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
2755 
2756   // Add L as type indicator
2757   int dest_index = 0;
2758   dest[dest_index++] = JVM_SIGNATURE_CLASS;
2759 
2760   // Add the actual class name
2761   for (int src_index = 0; src_index < src_length; ) {
2762     dest[dest_index++] = src[src_index++];
2763   }
2764 
2765   if (is_hidden()) { // Replace the last '+' with a '.'.
2766     for (int index = (int)src_length; index > 0; index--) {
2767       if (dest[index] == '+') {
2768         dest[index] = JVM_SIGNATURE_DOT;
2769         break;
2770       }
2771     }
2772   }
2773 
2774   // If we have a hash, append it
2775   for (int hash_index = 0; hash_index < hash_len; ) {
2776     dest[dest_index++] = hash_buf[hash_index++];
2777   }
2778 
2779   // Add the semicolon and the NULL
2780   dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
2781   dest[dest_index] = '\0';
2782   return dest;
2783 }
2784 
2785 ModuleEntry* InstanceKlass::module() const {
2786   // For an unsafe anonymous class return the host class' module
2787   if (is_unsafe_anonymous()) {
2788     assert(unsafe_anonymous_host() != NULL, "unsafe anonymous class must have a host class");
2789     return unsafe_anonymous_host()->module();
2790   }
2791 
2792   if (is_hidden() &&
2793       in_unnamed_package() &&
2794       class_loader_data()->has_class_mirror_holder()) {
2795     // For a non-strong hidden class defined to an unnamed package,
2796     // its (class held) CLD will not have an unnamed module created for it.
2797     // Two choices to find the correct ModuleEntry:
2798     // 1. If hidden class is within a nest, use nest host's module
2799     // 2. Find the unnamed module off from the class loader
2800     // For now option #2 is used since a nest host is not set until
2801     // after the instance class is created in jvm_lookup_define_class().
2802     if (class_loader_data()->is_boot_class_loader_data()) {
2803       return ClassLoaderData::the_null_class_loader_data()->unnamed_module();
2804     } else {
2805       oop module = java_lang_ClassLoader::unnamedModule(class_loader_data()->class_loader());
2806       assert(java_lang_Module::is_instance(module), "Not an instance of java.lang.Module");
2807       return java_lang_Module::module_entry(module);
2808     }
2809   }
2810 
2811   // Class is in a named package
2812   if (!in_unnamed_package()) {
2813     return _package_entry->module();
2814   }
2815 
2816   // Class is in an unnamed package, return its loader's unnamed module
2817   return class_loader_data()->unnamed_module();
2818 }
2819 
2820 void InstanceKlass::set_package(ClassLoaderData* loader_data, PackageEntry* pkg_entry, TRAPS) {
2821 
2822   // ensure java/ packages only loaded by boot or platform builtin loaders
2823   // not needed for shared class since CDS does not archive prohibited classes.
2824   if (!is_shared()) {
2825     check_prohibited_package(name(), loader_data, CHECK);
2826   }
2827 
2828   // ClassLoader::package_from_class_name has already incremented the refcount of the symbol
2829   // it returns, so we need to decrement it when the current function exits.
2830   TempNewSymbol from_class_name =
2831       (pkg_entry != NULL) ? NULL : ClassLoader::package_from_class_name(name());
2832 
2833   Symbol* pkg_name;
2834   if (pkg_entry != NULL) {
2835     pkg_name = pkg_entry->name();
2836   } else {
2837     pkg_name = from_class_name;
2838   }
2839 
2840   if (pkg_name != NULL && loader_data != NULL) {
2841 
2842     // Find in class loader's package entry table.
2843     _package_entry = pkg_entry != NULL ? pkg_entry : loader_data->packages()->lookup_only(pkg_name);
2844 
2845     // If the package name is not found in the loader's package
2846     // entry table, it is an indication that the package has not
2847     // been defined. Consider it defined within the unnamed module.
2848     if (_package_entry == NULL) {
2849 
2850       if (!ModuleEntryTable::javabase_defined()) {
2851         // Before java.base is defined during bootstrapping, define all packages in
2852         // the java.base module.  If a non-java.base package is erroneously placed
2853         // in the java.base module it will be caught later when java.base
2854         // is defined by ModuleEntryTable::verify_javabase_packages check.
2855         assert(ModuleEntryTable::javabase_moduleEntry() != NULL, JAVA_BASE_NAME " module is NULL");
2856         _package_entry = loader_data->packages()->lookup(pkg_name, ModuleEntryTable::javabase_moduleEntry());
2857       } else {
2858         assert(loader_data->unnamed_module() != NULL, "unnamed module is NULL");
2859         _package_entry = loader_data->packages()->lookup(pkg_name,
2860                                                          loader_data->unnamed_module());
2861       }
2862 
2863       // A package should have been successfully created
2864       DEBUG_ONLY(ResourceMark rm(THREAD));
2865       assert(_package_entry != NULL, "Package entry for class %s not found, loader %s",
2866              name()->as_C_string(), loader_data->loader_name_and_id());
2867     }
2868 
2869     if (log_is_enabled(Debug, module)) {
2870       ResourceMark rm(THREAD);
2871       ModuleEntry* m = _package_entry->module();
2872       log_trace(module)("Setting package: class: %s, package: %s, loader: %s, module: %s",
2873                         external_name(),
2874                         pkg_name->as_C_string(),
2875                         loader_data->loader_name_and_id(),
2876                         (m->is_named() ? m->name()->as_C_string() : UNNAMED_MODULE));
2877     }
2878   } else {
2879     ResourceMark rm(THREAD);
2880     log_trace(module)("Setting package: class: %s, package: unnamed, loader: %s, module: %s",
2881                       external_name(),
2882                       (loader_data != NULL) ? loader_data->loader_name_and_id() : "NULL",
2883                       UNNAMED_MODULE);
2884   }
2885 }
2886 
2887 // Function set_classpath_index checks if the package of the InstanceKlass is in the
2888 // boot loader's package entry table.  If so, then it sets the classpath_index
2889 // in the package entry record.
2890 //
2891 // The classpath_index field is used to find the entry on the boot loader class
2892 // path for packages with classes loaded by the boot loader from -Xbootclasspath/a
2893 // in an unnamed module.  It is also used to indicate (for all packages whose
2894 // classes are loaded by the boot loader) that at least one of the package's
2895 // classes has been loaded.
2896 void InstanceKlass::set_classpath_index(s2 path_index, TRAPS) {
2897   if (_package_entry != NULL) {
2898     DEBUG_ONLY(PackageEntryTable* pkg_entry_tbl = ClassLoaderData::the_null_class_loader_data()->packages();)
2899     assert(pkg_entry_tbl->lookup_only(_package_entry->name()) == _package_entry, "Should be same");
2900     assert(path_index != -1, "Unexpected classpath_index");
2901     _package_entry->set_classpath_index(path_index);
2902   }
2903 }
2904 
2905 // different versions of is_same_class_package
2906 
2907 bool InstanceKlass::is_same_class_package(const Klass* class2) const {
2908   oop classloader1 = this->class_loader();
2909   PackageEntry* classpkg1 = this->package();
2910   if (class2->is_objArray_klass()) {
2911     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
2912   }
2913 
2914   oop classloader2;
2915   PackageEntry* classpkg2;
2916   if (class2->is_instance_klass()) {
2917     classloader2 = class2->class_loader();
2918     classpkg2 = class2->package();
2919   } else {
2920     assert(class2->is_typeArray_klass(), "should be type array");
2921     classloader2 = NULL;
2922     classpkg2 = NULL;
2923   }
2924 
2925   // Same package is determined by comparing class loader
2926   // and package entries. Both must be the same. This rule
2927   // applies even to classes that are defined in the unnamed
2928   // package, they still must have the same class loader.
2929   if ((classloader1 == classloader2) && (classpkg1 == classpkg2)) {
2930     return true;
2931   }
2932 
2933   return false;
2934 }
2935 
2936 // return true if this class and other_class are in the same package. Classloader
2937 // and classname information is enough to determine a class's package
2938 bool InstanceKlass::is_same_class_package(oop other_class_loader,
2939                                           const Symbol* other_class_name) const {
2940   if (class_loader() != other_class_loader) {
2941     return false;
2942   }
2943   if (name()->fast_compare(other_class_name) == 0) {
2944      return true;
2945   }
2946 
2947   {
2948     ResourceMark rm;
2949 
2950     bool bad_class_name = false;
2951     TempNewSymbol other_pkg = ClassLoader::package_from_class_name(other_class_name, &bad_class_name);
2952     if (bad_class_name) {
2953       return false;
2954     }
2955     // Check that package_from_class_name() returns NULL, not "", if there is no package.
2956     assert(other_pkg == NULL || other_pkg->utf8_length() > 0, "package name is empty string");
2957 
2958     const Symbol* const this_package_name =
2959       this->package() != NULL ? this->package()->name() : NULL;
2960 
2961     if (this_package_name == NULL || other_pkg == NULL) {
2962       // One of the two doesn't have a package.  Only return true if the other
2963       // one also doesn't have a package.
2964       return this_package_name == other_pkg;
2965     }
2966 
2967     // Check if package is identical
2968     return this_package_name->fast_compare(other_pkg) == 0;
2969   }
2970 }
2971 
2972 // Returns true iff super_method can be overridden by a method in targetclassname
2973 // See JLS 3rd edition 8.4.6.1
2974 // Assumes name-signature match
2975 // "this" is InstanceKlass of super_method which must exist
2976 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
2977 bool InstanceKlass::is_override(const methodHandle& super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
2978    // Private methods can not be overridden
2979    if (super_method->is_private()) {
2980      return false;
2981    }
2982    // If super method is accessible, then override
2983    if ((super_method->is_protected()) ||
2984        (super_method->is_public())) {
2985      return true;
2986    }
2987    // Package-private methods are not inherited outside of package
2988    assert(super_method->is_package_private(), "must be package private");
2989    return(is_same_class_package(targetclassloader(), targetclassname));
2990 }
2991 
2992 // Only boot and platform class loaders can define classes in "java/" packages.
2993 void InstanceKlass::check_prohibited_package(Symbol* class_name,
2994                                              ClassLoaderData* loader_data,
2995                                              TRAPS) {
2996   if (!loader_data->is_boot_class_loader_data() &&
2997       !loader_data->is_platform_class_loader_data() &&
2998       class_name != NULL) {
2999     ResourceMark rm(THREAD);
3000     char* name = class_name->as_C_string();
3001     if (strncmp(name, JAVAPKG, JAVAPKG_LEN) == 0 && name[JAVAPKG_LEN] == '/') {
3002       TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name);
3003       assert(pkg_name != NULL, "Error in parsing package name starting with 'java/'");
3004       name = pkg_name->as_C_string();
3005       const char* class_loader_name = loader_data->loader_name_and_id();
3006       StringUtils::replace_no_expand(name, "/", ".");
3007       const char* msg_text1 = "Class loader (instance of): ";
3008       const char* msg_text2 = " tried to load prohibited package name: ";
3009       size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + strlen(name) + 1;
3010       char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len);
3011       jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, name);
3012       THROW_MSG(vmSymbols::java_lang_SecurityException(), message);
3013     }
3014   }
3015   return;
3016 }
3017 
3018 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3019   constantPoolHandle i_cp(THREAD, constants());
3020   for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3021     int ioff = iter.inner_class_info_index();
3022     if (ioff != 0) {
3023       // Check to see if the name matches the class we're looking for
3024       // before attempting to find the class.
3025       if (i_cp->klass_name_at_matches(this, ioff)) {
3026         Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3027         if (this == inner_klass) {
3028           *ooff = iter.outer_class_info_index();
3029           *noff = iter.inner_name_index();
3030           return true;
3031         }
3032       }
3033     }
3034   }
3035   return false;
3036 }
3037 
3038 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3039   InstanceKlass* outer_klass = NULL;
3040   *inner_is_member = false;
3041   int ooff = 0, noff = 0;
3042   bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3043   if (has_inner_classes_attr) {
3044     constantPoolHandle i_cp(THREAD, constants());
3045     if (ooff != 0) {
3046       Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3047       outer_klass = InstanceKlass::cast(ok);
3048       *inner_is_member = true;
3049     }
3050     if (NULL == outer_klass) {
3051       // It may be a local or anonymous class; try for that.
3052       int encl_method_class_idx = enclosing_method_class_index();
3053       if (encl_method_class_idx != 0) {
3054         Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
3055         outer_klass = InstanceKlass::cast(ok);
3056         *inner_is_member = false;
3057       }
3058     }
3059   }
3060 
3061   // If no inner class attribute found for this class.
3062   if (NULL == outer_klass) return NULL;
3063 
3064   // Throws an exception if outer klass has not declared k as an inner klass
3065   // We need evidence that each klass knows about the other, or else
3066   // the system could allow a spoof of an inner class to gain access rights.
3067   Reflection::check_for_inner_class(outer_klass, this, *inner_is_member, CHECK_NULL);
3068   return outer_klass;
3069 }
3070 
3071 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
3072   jint access = access_flags().as_int();
3073 
3074   // But check if it happens to be member class.
3075   InnerClassesIterator iter(this);
3076   for (; !iter.done(); iter.next()) {
3077     int ioff = iter.inner_class_info_index();
3078     // Inner class attribute can be zero, skip it.
3079     // Strange but true:  JVM spec. allows null inner class refs.
3080     if (ioff == 0) continue;
3081 
3082     // only look at classes that are already loaded
3083     // since we are looking for the flags for our self.
3084     Symbol* inner_name = constants()->klass_name_at(ioff);
3085     if (name() == inner_name) {
3086       // This is really a member class.
3087       access = iter.inner_access_flags();
3088       break;
3089     }
3090   }
3091   // Remember to strip ACC_SUPER bit
3092   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
3093 }
3094 
3095 jint InstanceKlass::jvmti_class_status() const {
3096   jint result = 0;
3097 
3098   if (is_linked()) {
3099     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3100   }
3101 
3102   if (is_initialized()) {
3103     assert(is_linked(), "Class status is not consistent");
3104     result |= JVMTI_CLASS_STATUS_INITIALIZED;
3105   }
3106   if (is_in_error_state()) {
3107     result |= JVMTI_CLASS_STATUS_ERROR;
3108   }
3109   return result;
3110 }
3111 
3112 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
3113   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
3114   int method_table_offset_in_words = ioe->offset()/wordSize;
3115   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
3116                        / itableOffsetEntry::size();
3117 
3118   for (int cnt = 0 ; ; cnt ++, ioe ++) {
3119     // If the interface isn't implemented by the receiver class,
3120     // the VM should throw IncompatibleClassChangeError.
3121     if (cnt >= nof_interfaces) {
3122       ResourceMark rm(THREAD);
3123       stringStream ss;
3124       bool same_module = (module() == holder->module());
3125       ss.print("Receiver class %s does not implement "
3126                "the interface %s defining the method to be called "
3127                "(%s%s%s)",
3128                external_name(), holder->external_name(),
3129                (same_module) ? joint_in_module_of_loader(holder) : class_in_module_of_loader(),
3130                (same_module) ? "" : "; ",
3131                (same_module) ? "" : holder->class_in_module_of_loader());
3132       THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
3133     }
3134 
3135     Klass* ik = ioe->interface_klass();
3136     if (ik == holder) break;
3137   }
3138 
3139   itableMethodEntry* ime = ioe->first_method_entry(this);
3140   Method* m = ime[index].method();
3141   if (m == NULL) {
3142     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
3143   }
3144   return m;
3145 }
3146 
3147 
3148 #if INCLUDE_JVMTI
3149 // update default_methods for redefineclasses for methods that are
3150 // not yet in the vtable due to concurrent subclass define and superinterface
3151 // redefinition
3152 // Note: those in the vtable, should have been updated via adjust_method_entries
3153 void InstanceKlass::adjust_default_methods(bool* trace_name_printed) {
3154   // search the default_methods for uses of either obsolete or EMCP methods
3155   if (default_methods() != NULL) {
3156     for (int index = 0; index < default_methods()->length(); index ++) {
3157       Method* old_method = default_methods()->at(index);
3158       if (old_method == NULL || !old_method->is_old()) {
3159         continue; // skip uninteresting entries
3160       }
3161       assert(!old_method->is_deleted(), "default methods may not be deleted");
3162       Method* new_method = old_method->get_new_method();
3163       default_methods()->at_put(index, new_method);
3164 
3165       if (log_is_enabled(Info, redefine, class, update)) {
3166         ResourceMark rm;
3167         if (!(*trace_name_printed)) {
3168           log_info(redefine, class, update)
3169             ("adjust: klassname=%s default methods from name=%s",
3170              external_name(), old_method->method_holder()->external_name());
3171           *trace_name_printed = true;
3172         }
3173         log_debug(redefine, class, update, vtables)
3174           ("default method update: %s(%s) ",
3175            new_method->name()->as_C_string(), new_method->signature()->as_C_string());
3176       }
3177     }
3178   }
3179 }
3180 #endif // INCLUDE_JVMTI
3181 
3182 // On-stack replacement stuff
3183 void InstanceKlass::add_osr_nmethod(nmethod* n) {
3184   assert_lock_strong(CompiledMethod_lock);
3185 #ifndef PRODUCT
3186   if (TieredCompilation) {
3187     nmethod* prev = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), n->comp_level(), true);
3188     assert(prev == NULL || !prev->is_in_use() COMPILER2_PRESENT(|| StressRecompilation),
3189            "redundant OSR recompilation detected. memory leak in CodeCache!");
3190   }
3191 #endif
3192   // only one compilation can be active
3193   {
3194     assert(n->is_osr_method(), "wrong kind of nmethod");
3195     n->set_osr_link(osr_nmethods_head());
3196     set_osr_nmethods_head(n);
3197     // Raise the highest osr level if necessary
3198     if (TieredCompilation) {
3199       Method* m = n->method();
3200       m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
3201     }
3202   }
3203 
3204   // Get rid of the osr methods for the same bci that have lower levels.
3205   if (TieredCompilation) {
3206     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
3207       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
3208       if (inv != NULL && inv->is_in_use()) {
3209         inv->make_not_entrant();
3210       }
3211     }
3212   }
3213 }
3214 
3215 // Remove osr nmethod from the list. Return true if found and removed.
3216 bool InstanceKlass::remove_osr_nmethod(nmethod* n) {
3217   // This is a short non-blocking critical region, so the no safepoint check is ok.
3218   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock
3219                  , Mutex::_no_safepoint_check_flag);
3220   assert(n->is_osr_method(), "wrong kind of nmethod");
3221   nmethod* last = NULL;
3222   nmethod* cur  = osr_nmethods_head();
3223   int max_level = CompLevel_none;  // Find the max comp level excluding n
3224   Method* m = n->method();
3225   // Search for match
3226   bool found = false;
3227   while(cur != NULL && cur != n) {
3228     if (TieredCompilation && m == cur->method()) {
3229       // Find max level before n
3230       max_level = MAX2(max_level, cur->comp_level());
3231     }
3232     last = cur;
3233     cur = cur->osr_link();
3234   }
3235   nmethod* next = NULL;
3236   if (cur == n) {
3237     found = true;
3238     next = cur->osr_link();
3239     if (last == NULL) {
3240       // Remove first element
3241       set_osr_nmethods_head(next);
3242     } else {
3243       last->set_osr_link(next);
3244     }
3245   }
3246   n->set_osr_link(NULL);
3247   if (TieredCompilation) {
3248     cur = next;
3249     while (cur != NULL) {
3250       // Find max level after n
3251       if (m == cur->method()) {
3252         max_level = MAX2(max_level, cur->comp_level());
3253       }
3254       cur = cur->osr_link();
3255     }
3256     m->set_highest_osr_comp_level(max_level);
3257   }
3258   return found;
3259 }
3260 
3261 int InstanceKlass::mark_osr_nmethods(const Method* m) {
3262   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock,
3263                  Mutex::_no_safepoint_check_flag);
3264   nmethod* osr = osr_nmethods_head();
3265   int found = 0;
3266   while (osr != NULL) {
3267     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3268     if (osr->method() == m) {
3269       osr->mark_for_deoptimization();
3270       found++;
3271     }
3272     osr = osr->osr_link();
3273   }
3274   return found;
3275 }
3276 
3277 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
3278   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock,
3279                  Mutex::_no_safepoint_check_flag);
3280   nmethod* osr = osr_nmethods_head();
3281   nmethod* best = NULL;
3282   while (osr != NULL) {
3283     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3284     // There can be a time when a c1 osr method exists but we are waiting
3285     // for a c2 version. When c2 completes its osr nmethod we will trash
3286     // the c1 version and only be able to find the c2 version. However
3287     // while we overflow in the c1 code at back branches we don't want to
3288     // try and switch to the same code as we are already running
3289 
3290     if (osr->method() == m &&
3291         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
3292       if (match_level) {
3293         if (osr->comp_level() == comp_level) {
3294           // Found a match - return it.
3295           return osr;
3296         }
3297       } else {
3298         if (best == NULL || (osr->comp_level() > best->comp_level())) {
3299           if (osr->comp_level() == CompLevel_highest_tier) {
3300             // Found the best possible - return it.
3301             return osr;
3302           }
3303           best = osr;
3304         }
3305       }
3306     }
3307     osr = osr->osr_link();
3308   }
3309 
3310   assert(match_level == false || best == NULL, "shouldn't pick up anything if match_level is set");
3311   if (best != NULL && best->comp_level() >= comp_level) {
3312     return best;
3313   }
3314   return NULL;
3315 }
3316 
3317 // -----------------------------------------------------------------------------------------------------
3318 // Printing
3319 
3320 #ifndef PRODUCT
3321 
3322 #define BULLET  " - "
3323 
3324 static const char* state_names[] = {
3325   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3326 };
3327 
3328 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3329   for (int i = 0; i < len; i++) {
3330     intptr_t e = start[i];
3331     st->print("%d : " INTPTR_FORMAT, i, e);
3332     if (MetaspaceObj::is_valid((Metadata*)e)) {
3333       st->print(" ");
3334       ((Metadata*)e)->print_value_on(st);
3335     }
3336     st->cr();
3337   }
3338 }
3339 
3340 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3341   return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3342 }
3343 
3344 void InstanceKlass::print_on(outputStream* st) const {
3345   assert(is_klass(), "must be klass");
3346   Klass::print_on(st);
3347 
3348   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3349   st->print(BULLET"klass size:        %d", size());                               st->cr();
3350   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
3351   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
3352   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3353   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3354   st->print(BULLET"sub:               ");
3355   Klass* sub = subklass();
3356   int n;
3357   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
3358     if (n < MaxSubklassPrintSize) {
3359       sub->print_value_on(st);
3360       st->print("   ");
3361     }
3362   }
3363   if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize);
3364   st->cr();
3365 
3366   if (is_interface()) {
3367     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
3368     if (nof_implementors() == 1) {
3369       st->print_cr(BULLET"implementor:    ");
3370       st->print("   ");
3371       implementor()->print_value_on(st);
3372       st->cr();
3373     }
3374   }
3375 
3376   st->print(BULLET"arrays:            "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3377   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
3378   if (Verbose || WizardMode) {
3379     Array<Method*>* method_array = methods();
3380     for (int i = 0; i < method_array->length(); i++) {
3381       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3382     }
3383   }
3384   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
3385   st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
3386   if (Verbose && default_methods() != NULL) {
3387     Array<Method*>* method_array = default_methods();
3388     for (int i = 0; i < method_array->length(); i++) {
3389       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3390     }
3391   }
3392   if (default_vtable_indices() != NULL) {
3393     st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
3394   }
3395   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
3396   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3397   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
3398   if (class_loader_data() != NULL) {
3399     st->print(BULLET"class loader data:  ");
3400     class_loader_data()->print_value_on(st);
3401     st->cr();
3402   }
3403   st->print(BULLET"unsafe anonymous host class:        "); Metadata::print_value_on_maybe_null(st, unsafe_anonymous_host()); st->cr();
3404   if (source_file_name() != NULL) {
3405     st->print(BULLET"source file:       ");
3406     source_file_name()->print_value_on(st);
3407     st->cr();
3408   }
3409   if (source_debug_extension() != NULL) {
3410     st->print(BULLET"source debug extension:       ");
3411     st->print("%s", source_debug_extension());
3412     st->cr();
3413   }
3414   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
3415   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
3416   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
3417   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
3418   {
3419     bool have_pv = false;
3420     // previous versions are linked together through the InstanceKlass
3421     for (InstanceKlass* pv_node = previous_versions();
3422          pv_node != NULL;
3423          pv_node = pv_node->previous_versions()) {
3424       if (!have_pv)
3425         st->print(BULLET"previous version:  ");
3426       have_pv = true;
3427       pv_node->constants()->print_value_on(st);
3428     }
3429     if (have_pv) st->cr();
3430   }
3431 
3432   if (generic_signature() != NULL) {
3433     st->print(BULLET"generic signature: ");
3434     generic_signature()->print_value_on(st);
3435     st->cr();
3436   }
3437   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
3438   st->print(BULLET"nest members:     "); nest_members()->print_value_on(st);     st->cr();
3439   if (record_components() != NULL) {
3440     st->print(BULLET"record components:     "); record_components()->print_value_on(st);     st->cr();
3441   }
3442   st->print(BULLET"permitted subclasses:     "); permitted_subclasses()->print_value_on(st);     st->cr();
3443   if (java_mirror() != NULL) {
3444     st->print(BULLET"java mirror:       ");
3445     java_mirror()->print_value_on(st);
3446     st->cr();
3447   } else {
3448     st->print_cr(BULLET"java mirror:       NULL");
3449   }
3450   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3451   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
3452   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3453   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
3454   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3455   FieldPrinter print_static_field(st);
3456   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3457   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3458   FieldPrinter print_nonstatic_field(st);
3459   InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3460   ik->do_nonstatic_fields(&print_nonstatic_field);
3461 
3462   st->print(BULLET"non-static oop maps: ");
3463   OopMapBlock* map     = start_of_nonstatic_oop_maps();
3464   OopMapBlock* end_map = map + nonstatic_oop_map_count();
3465   while (map < end_map) {
3466     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3467     map++;
3468   }
3469   st->cr();
3470 }
3471 
3472 #endif //PRODUCT
3473 
3474 void InstanceKlass::print_value_on(outputStream* st) const {
3475   assert(is_klass(), "must be klass");
3476   if (Verbose || WizardMode)  access_flags().print_on(st);
3477   name()->print_value_on(st);
3478 }
3479 
3480 #ifndef PRODUCT
3481 
3482 void FieldPrinter::do_field(fieldDescriptor* fd) {
3483   _st->print(BULLET);
3484    if (_obj == NULL) {
3485      fd->print_on(_st);
3486      _st->cr();
3487    } else {
3488      fd->print_on_for(_st, _obj);
3489      _st->cr();
3490    }
3491 }
3492 
3493 
3494 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3495   Klass::oop_print_on(obj, st);
3496 
3497   if (this == SystemDictionary::String_klass()) {
3498     typeArrayOop value  = java_lang_String::value(obj);
3499     juint        length = java_lang_String::length(obj);
3500     if (value != NULL &&
3501         value->is_typeArray() &&
3502         length <= (juint) value->length()) {
3503       st->print(BULLET"string: ");
3504       java_lang_String::print(obj, st);
3505       st->cr();
3506       if (!WizardMode)  return;  // that is enough
3507     }
3508   }
3509 
3510   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
3511   FieldPrinter print_field(st, obj);
3512   do_nonstatic_fields(&print_field);
3513 
3514   if (this == SystemDictionary::Class_klass()) {
3515     st->print(BULLET"signature: ");
3516     java_lang_Class::print_signature(obj, st);
3517     st->cr();
3518     Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
3519     st->print(BULLET"fake entry for mirror: ");
3520     Metadata::print_value_on_maybe_null(st, mirrored_klass);
3521     st->cr();
3522     Klass* array_klass = java_lang_Class::array_klass_acquire(obj);
3523     st->print(BULLET"fake entry for array: ");
3524     Metadata::print_value_on_maybe_null(st, array_klass);
3525     st->cr();
3526     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
3527     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
3528     Klass* real_klass = java_lang_Class::as_Klass(obj);
3529     if (real_klass != NULL && real_klass->is_instance_klass()) {
3530       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3531     }
3532   } else if (this == SystemDictionary::MethodType_klass()) {
3533     st->print(BULLET"signature: ");
3534     java_lang_invoke_MethodType::print_signature(obj, st);
3535     st->cr();
3536   }
3537 }
3538 
3539 bool InstanceKlass::verify_itable_index(int i) {
3540   int method_count = klassItable::method_count_for_interface(this);
3541   assert(i >= 0 && i < method_count, "index out of bounds");
3542   return true;
3543 }
3544 
3545 #endif //PRODUCT
3546 
3547 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
3548   st->print("a ");
3549   name()->print_value_on(st);
3550   obj->print_address_on(st);
3551   if (this == SystemDictionary::String_klass()
3552       && java_lang_String::value(obj) != NULL) {
3553     ResourceMark rm;
3554     int len = java_lang_String::length(obj);
3555     int plen = (len < 24 ? len : 12);
3556     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
3557     st->print(" = \"%s\"", str);
3558     if (len > plen)
3559       st->print("...[%d]", len);
3560   } else if (this == SystemDictionary::Class_klass()) {
3561     Klass* k = java_lang_Class::as_Klass(obj);
3562     st->print(" = ");
3563     if (k != NULL) {
3564       k->print_value_on(st);
3565     } else {
3566       const char* tname = type2name(java_lang_Class::primitive_type(obj));
3567       st->print("%s", tname ? tname : "type?");
3568     }
3569   } else if (this == SystemDictionary::MethodType_klass()) {
3570     st->print(" = ");
3571     java_lang_invoke_MethodType::print_signature(obj, st);
3572   } else if (java_lang_boxing_object::is_instance(obj)) {
3573     st->print(" = ");
3574     java_lang_boxing_object::print(obj, st);
3575   } else if (this == SystemDictionary::LambdaForm_klass()) {
3576     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
3577     if (vmentry != NULL) {
3578       st->print(" => ");
3579       vmentry->print_value_on(st);
3580     }
3581   } else if (this == SystemDictionary::MemberName_klass()) {
3582     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
3583     if (vmtarget != NULL) {
3584       st->print(" = ");
3585       vmtarget->print_value_on(st);
3586     } else {
3587       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
3588       st->print(".");
3589       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
3590     }
3591   }
3592 }
3593 
3594 const char* InstanceKlass::internal_name() const {
3595   return external_name();
3596 }
3597 
3598 void InstanceKlass::print_class_load_logging(ClassLoaderData* loader_data,
3599                                              const char* module_name,
3600                                              const ClassFileStream* cfs) const {
3601   if (!log_is_enabled(Info, class, load)) {
3602     return;
3603   }
3604 
3605   ResourceMark rm;
3606   LogMessage(class, load) msg;
3607   stringStream info_stream;
3608 
3609   // Name and class hierarchy info
3610   info_stream.print("%s", external_name());
3611 
3612   // Source
3613   if (cfs != NULL) {
3614     if (cfs->source() != NULL) {
3615       if (module_name != NULL) {
3616         // When the boot loader created the stream, it didn't know the module name
3617         // yet. Let's format it now.
3618         if (cfs->from_boot_loader_modules_image()) {
3619           info_stream.print(" source: jrt:/%s", module_name);
3620         } else {
3621           info_stream.print(" source: %s", cfs->source());
3622         }
3623       } else {
3624         info_stream.print(" source: %s", cfs->source());
3625       }
3626     } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) {
3627       Thread* THREAD = Thread::current();
3628       Klass* caller =
3629             THREAD->is_Java_thread()
3630                 ? ((JavaThread*)THREAD)->security_get_caller_class(1)
3631                 : NULL;
3632       // caller can be NULL, for example, during a JVMTI VM_Init hook
3633       if (caller != NULL) {
3634         info_stream.print(" source: instance of %s", caller->external_name());
3635       } else {
3636         // source is unknown
3637       }
3638     } else {
3639       oop class_loader = loader_data->class_loader();
3640       info_stream.print(" source: %s", class_loader->klass()->external_name());
3641     }
3642   } else {
3643     assert(this->is_shared(), "must be");
3644     if (MetaspaceShared::is_shared_dynamic((void*)this)) {
3645       info_stream.print(" source: shared objects file (top)");
3646     } else {
3647       info_stream.print(" source: shared objects file");
3648     }
3649   }
3650 
3651   msg.info("%s", info_stream.as_string());
3652 
3653   if (log_is_enabled(Debug, class, load)) {
3654     stringStream debug_stream;
3655 
3656     // Class hierarchy info
3657     debug_stream.print(" klass: " INTPTR_FORMAT " super: " INTPTR_FORMAT,
3658                        p2i(this),  p2i(superklass()));
3659 
3660     // Interfaces
3661     if (local_interfaces() != NULL && local_interfaces()->length() > 0) {
3662       debug_stream.print(" interfaces:");
3663       int length = local_interfaces()->length();
3664       for (int i = 0; i < length; i++) {
3665         debug_stream.print(" " INTPTR_FORMAT,
3666                            p2i(InstanceKlass::cast(local_interfaces()->at(i))));
3667       }
3668     }
3669 
3670     // Class loader
3671     debug_stream.print(" loader: [");
3672     loader_data->print_value_on(&debug_stream);
3673     debug_stream.print("]");
3674 
3675     // Classfile checksum
3676     if (cfs) {
3677       debug_stream.print(" bytes: %d checksum: %08x",
3678                          cfs->length(),
3679                          ClassLoader::crc32(0, (const char*)cfs->buffer(),
3680                          cfs->length()));
3681     }
3682 
3683     msg.debug("%s", debug_stream.as_string());
3684   }
3685 }
3686 
3687 // Verification
3688 
3689 class VerifyFieldClosure: public BasicOopIterateClosure {
3690  protected:
3691   template <class T> void do_oop_work(T* p) {
3692     oop obj = RawAccess<>::oop_load(p);
3693     if (!oopDesc::is_oop_or_null(obj)) {
3694       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj));
3695       Universe::print_on(tty);
3696       guarantee(false, "boom");
3697     }
3698   }
3699  public:
3700   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
3701   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
3702 };
3703 
3704 void InstanceKlass::verify_on(outputStream* st) {
3705 #ifndef PRODUCT
3706   // Avoid redundant verifies, this really should be in product.
3707   if (_verify_count == Universe::verify_count()) return;
3708   _verify_count = Universe::verify_count();
3709 #endif
3710 
3711   // Verify Klass
3712   Klass::verify_on(st);
3713 
3714   // Verify that klass is present in ClassLoaderData
3715   guarantee(class_loader_data()->contains_klass(this),
3716             "this class isn't found in class loader data");
3717 
3718   // Verify vtables
3719   if (is_linked()) {
3720     // $$$ This used to be done only for m/s collections.  Doing it
3721     // always seemed a valid generalization.  (DLD -- 6/00)
3722     vtable().verify(st);
3723   }
3724 
3725   // Verify first subklass
3726   if (subklass() != NULL) {
3727     guarantee(subklass()->is_klass(), "should be klass");
3728   }
3729 
3730   // Verify siblings
3731   Klass* super = this->super();
3732   Klass* sib = next_sibling();
3733   if (sib != NULL) {
3734     if (sib == this) {
3735       fatal("subclass points to itself " PTR_FORMAT, p2i(sib));
3736     }
3737 
3738     guarantee(sib->is_klass(), "should be klass");
3739     guarantee(sib->super() == super, "siblings should have same superklass");
3740   }
3741 
3742   // Verify local interfaces
3743   if (local_interfaces()) {
3744     Array<InstanceKlass*>* local_interfaces = this->local_interfaces();
3745     for (int j = 0; j < local_interfaces->length(); j++) {
3746       InstanceKlass* e = local_interfaces->at(j);
3747       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
3748     }
3749   }
3750 
3751   // Verify transitive interfaces
3752   if (transitive_interfaces() != NULL) {
3753     Array<InstanceKlass*>* transitive_interfaces = this->transitive_interfaces();
3754     for (int j = 0; j < transitive_interfaces->length(); j++) {
3755       InstanceKlass* e = transitive_interfaces->at(j);
3756       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
3757     }
3758   }
3759 
3760   // Verify methods
3761   if (methods() != NULL) {
3762     Array<Method*>* methods = this->methods();
3763     for (int j = 0; j < methods->length(); j++) {
3764       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3765     }
3766     for (int j = 0; j < methods->length() - 1; j++) {
3767       Method* m1 = methods->at(j);
3768       Method* m2 = methods->at(j + 1);
3769       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3770     }
3771   }
3772 
3773   // Verify method ordering
3774   if (method_ordering() != NULL) {
3775     Array<int>* method_ordering = this->method_ordering();
3776     int length = method_ordering->length();
3777     if (JvmtiExport::can_maintain_original_method_order() ||
3778         ((UseSharedSpaces || Arguments::is_dumping_archive()) && length != 0)) {
3779       guarantee(length == methods()->length(), "invalid method ordering length");
3780       jlong sum = 0;
3781       for (int j = 0; j < length; j++) {
3782         int original_index = method_ordering->at(j);
3783         guarantee(original_index >= 0, "invalid method ordering index");
3784         guarantee(original_index < length, "invalid method ordering index");
3785         sum += original_index;
3786       }
3787       // Verify sum of indices 0,1,...,length-1
3788       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
3789     } else {
3790       guarantee(length == 0, "invalid method ordering length");
3791     }
3792   }
3793 
3794   // Verify default methods
3795   if (default_methods() != NULL) {
3796     Array<Method*>* methods = this->default_methods();
3797     for (int j = 0; j < methods->length(); j++) {
3798       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3799     }
3800     for (int j = 0; j < methods->length() - 1; j++) {
3801       Method* m1 = methods->at(j);
3802       Method* m2 = methods->at(j + 1);
3803       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3804     }
3805   }
3806 
3807   // Verify JNI static field identifiers
3808   if (jni_ids() != NULL) {
3809     jni_ids()->verify(this);
3810   }
3811 
3812   // Verify other fields
3813   if (constants() != NULL) {
3814     guarantee(constants()->is_constantPool(), "should be constant pool");
3815   }
3816   const Klass* anonymous_host = unsafe_anonymous_host();
3817   if (anonymous_host != NULL) {
3818     guarantee(anonymous_host->is_klass(), "should be klass");
3819   }
3820 }
3821 
3822 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
3823   Klass::oop_verify_on(obj, st);
3824   VerifyFieldClosure blk;
3825   obj->oop_iterate(&blk);
3826 }
3827 
3828 
3829 // JNIid class for jfieldIDs only
3830 // Note to reviewers:
3831 // These JNI functions are just moved over to column 1 and not changed
3832 // in the compressed oops workspace.
3833 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
3834   _holder = holder;
3835   _offset = offset;
3836   _next = next;
3837   debug_only(_is_static_field_id = false;)
3838 }
3839 
3840 
3841 JNIid* JNIid::find(int offset) {
3842   JNIid* current = this;
3843   while (current != NULL) {
3844     if (current->offset() == offset) return current;
3845     current = current->next();
3846   }
3847   return NULL;
3848 }
3849 
3850 void JNIid::deallocate(JNIid* current) {
3851   while (current != NULL) {
3852     JNIid* next = current->next();
3853     delete current;
3854     current = next;
3855   }
3856 }
3857 
3858 
3859 void JNIid::verify(Klass* holder) {
3860   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
3861   int end_field_offset;
3862   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
3863 
3864   JNIid* current = this;
3865   while (current != NULL) {
3866     guarantee(current->holder() == holder, "Invalid klass in JNIid");
3867 #ifdef ASSERT
3868     int o = current->offset();
3869     if (current->is_static_field_id()) {
3870       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
3871     }
3872 #endif
3873     current = current->next();
3874   }
3875 }
3876 
3877 void InstanceKlass::set_init_state(ClassState state) {
3878 #ifdef ASSERT
3879   bool good_state = is_shared() ? (_init_state <= state)
3880                                                : (_init_state < state);
3881   assert(good_state || state == allocated, "illegal state transition");
3882 #endif
3883   assert(_init_thread == NULL, "should be cleared before state change");
3884   _init_state = (u1)state;
3885 }
3886 
3887 #if INCLUDE_JVMTI
3888 
3889 // RedefineClasses() support for previous versions
3890 
3891 // Globally, there is at least one previous version of a class to walk
3892 // during class unloading, which is saved because old methods in the class
3893 // are still running.   Otherwise the previous version list is cleaned up.
3894 bool InstanceKlass::_has_previous_versions = false;
3895 
3896 // Returns true if there are previous versions of a class for class
3897 // unloading only. Also resets the flag to false. purge_previous_version
3898 // will set the flag to true if there are any left, i.e., if there's any
3899 // work to do for next time. This is to avoid the expensive code cache
3900 // walk in CLDG::clean_deallocate_lists().
3901 bool InstanceKlass::has_previous_versions_and_reset() {
3902   bool ret = _has_previous_versions;
3903   log_trace(redefine, class, iklass, purge)("Class unloading: has_previous_versions = %s",
3904      ret ? "true" : "false");
3905   _has_previous_versions = false;
3906   return ret;
3907 }
3908 
3909 // Purge previous versions before adding new previous versions of the class and
3910 // during class unloading.
3911 void InstanceKlass::purge_previous_version_list() {
3912   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
3913   assert(has_been_redefined(), "Should only be called for main class");
3914 
3915   // Quick exit.
3916   if (previous_versions() == NULL) {
3917     return;
3918   }
3919 
3920   // This klass has previous versions so see what we can cleanup
3921   // while it is safe to do so.
3922 
3923   int deleted_count = 0;    // leave debugging breadcrumbs
3924   int live_count = 0;
3925   ClassLoaderData* loader_data = class_loader_data();
3926   assert(loader_data != NULL, "should never be null");
3927 
3928   ResourceMark rm;
3929   log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name());
3930 
3931   // previous versions are linked together through the InstanceKlass
3932   InstanceKlass* pv_node = previous_versions();
3933   InstanceKlass* last = this;
3934   int version = 0;
3935 
3936   // check the previous versions list
3937   for (; pv_node != NULL; ) {
3938 
3939     ConstantPool* pvcp = pv_node->constants();
3940     assert(pvcp != NULL, "cp ref was unexpectedly cleared");
3941 
3942     if (!pvcp->on_stack()) {
3943       // If the constant pool isn't on stack, none of the methods
3944       // are executing.  Unlink this previous_version.
3945       // The previous version InstanceKlass is on the ClassLoaderData deallocate list
3946       // so will be deallocated during the next phase of class unloading.
3947       log_trace(redefine, class, iklass, purge)
3948         ("previous version " INTPTR_FORMAT " is dead.", p2i(pv_node));
3949       // For debugging purposes.
3950       pv_node->set_is_scratch_class();
3951       // Unlink from previous version list.
3952       assert(pv_node->class_loader_data() == loader_data, "wrong loader_data");
3953       InstanceKlass* next = pv_node->previous_versions();
3954       pv_node->link_previous_versions(NULL);   // point next to NULL
3955       last->link_previous_versions(next);
3956       // Add to the deallocate list after unlinking
3957       loader_data->add_to_deallocate_list(pv_node);
3958       pv_node = next;
3959       deleted_count++;
3960       version++;
3961       continue;
3962     } else {
3963       log_trace(redefine, class, iklass, purge)("previous version " INTPTR_FORMAT " is alive", p2i(pv_node));
3964       assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
3965       guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
3966       live_count++;
3967       // found a previous version for next time we do class unloading
3968       _has_previous_versions = true;
3969     }
3970 
3971     // At least one method is live in this previous version.
3972     // Reset dead EMCP methods not to get breakpoints.
3973     // All methods are deallocated when all of the methods for this class are no
3974     // longer running.
3975     Array<Method*>* method_refs = pv_node->methods();
3976     if (method_refs != NULL) {
3977       log_trace(redefine, class, iklass, purge)("previous methods length=%d", method_refs->length());
3978       for (int j = 0; j < method_refs->length(); j++) {
3979         Method* method = method_refs->at(j);
3980 
3981         if (!method->on_stack()) {
3982           // no breakpoints for non-running methods
3983           if (method->is_running_emcp()) {
3984             method->set_running_emcp(false);
3985           }
3986         } else {
3987           assert (method->is_obsolete() || method->is_running_emcp(),
3988                   "emcp method cannot run after emcp bit is cleared");
3989           log_trace(redefine, class, iklass, purge)
3990             ("purge: %s(%s): prev method @%d in version @%d is alive",
3991              method->name()->as_C_string(), method->signature()->as_C_string(), j, version);
3992         }
3993       }
3994     }
3995     // next previous version
3996     last = pv_node;
3997     pv_node = pv_node->previous_versions();
3998     version++;
3999   }
4000   log_trace(redefine, class, iklass, purge)
4001     ("previous version stats: live=%d, deleted=%d", live_count, deleted_count);
4002 }
4003 
4004 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,
4005                                                 int emcp_method_count) {
4006   int obsolete_method_count = old_methods->length() - emcp_method_count;
4007 
4008   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
4009       _previous_versions != NULL) {
4010     // We have a mix of obsolete and EMCP methods so we have to
4011     // clear out any matching EMCP method entries the hard way.
4012     int local_count = 0;
4013     for (int i = 0; i < old_methods->length(); i++) {
4014       Method* old_method = old_methods->at(i);
4015       if (old_method->is_obsolete()) {
4016         // only obsolete methods are interesting
4017         Symbol* m_name = old_method->name();
4018         Symbol* m_signature = old_method->signature();
4019 
4020         // previous versions are linked together through the InstanceKlass
4021         int j = 0;
4022         for (InstanceKlass* prev_version = _previous_versions;
4023              prev_version != NULL;
4024              prev_version = prev_version->previous_versions(), j++) {
4025 
4026           Array<Method*>* method_refs = prev_version->methods();
4027           for (int k = 0; k < method_refs->length(); k++) {
4028             Method* method = method_refs->at(k);
4029 
4030             if (!method->is_obsolete() &&
4031                 method->name() == m_name &&
4032                 method->signature() == m_signature) {
4033               // The current RedefineClasses() call has made all EMCP
4034               // versions of this method obsolete so mark it as obsolete
4035               log_trace(redefine, class, iklass, add)
4036                 ("%s(%s): flush obsolete method @%d in version @%d",
4037                  m_name->as_C_string(), m_signature->as_C_string(), k, j);
4038 
4039               method->set_is_obsolete();
4040               break;
4041             }
4042           }
4043 
4044           // The previous loop may not find a matching EMCP method, but
4045           // that doesn't mean that we can optimize and not go any
4046           // further back in the PreviousVersion generations. The EMCP
4047           // method for this generation could have already been made obsolete,
4048           // but there still may be an older EMCP method that has not
4049           // been made obsolete.
4050         }
4051 
4052         if (++local_count >= obsolete_method_count) {
4053           // no more obsolete methods so bail out now
4054           break;
4055         }
4056       }
4057     }
4058   }
4059 }
4060 
4061 // Save the scratch_class as the previous version if any of the methods are running.
4062 // The previous_versions are used to set breakpoints in EMCP methods and they are
4063 // also used to clean MethodData links to redefined methods that are no longer running.
4064 void InstanceKlass::add_previous_version(InstanceKlass* scratch_class,
4065                                          int emcp_method_count) {
4066   assert(Thread::current()->is_VM_thread(),
4067          "only VMThread can add previous versions");
4068 
4069   ResourceMark rm;
4070   log_trace(redefine, class, iklass, add)
4071     ("adding previous version ref for %s, EMCP_cnt=%d", scratch_class->external_name(), emcp_method_count);
4072 
4073   // Clean out old previous versions for this class
4074   purge_previous_version_list();
4075 
4076   // Mark newly obsolete methods in remaining previous versions.  An EMCP method from
4077   // a previous redefinition may be made obsolete by this redefinition.
4078   Array<Method*>* old_methods = scratch_class->methods();
4079   mark_newly_obsolete_methods(old_methods, emcp_method_count);
4080 
4081   // If the constant pool for this previous version of the class
4082   // is not marked as being on the stack, then none of the methods
4083   // in this previous version of the class are on the stack so
4084   // we don't need to add this as a previous version.
4085   ConstantPool* cp_ref = scratch_class->constants();
4086   if (!cp_ref->on_stack()) {
4087     log_trace(redefine, class, iklass, add)("scratch class not added; no methods are running");
4088     // For debugging purposes.
4089     scratch_class->set_is_scratch_class();
4090     scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class);
4091     return;
4092   }
4093 
4094   if (emcp_method_count != 0) {
4095     // At least one method is still running, check for EMCP methods
4096     for (int i = 0; i < old_methods->length(); i++) {
4097       Method* old_method = old_methods->at(i);
4098       if (!old_method->is_obsolete() && old_method->on_stack()) {
4099         // if EMCP method (not obsolete) is on the stack, mark as EMCP so that
4100         // we can add breakpoints for it.
4101 
4102         // We set the method->on_stack bit during safepoints for class redefinition
4103         // and use this bit to set the is_running_emcp bit.
4104         // After the safepoint, the on_stack bit is cleared and the running emcp
4105         // method may exit.   If so, we would set a breakpoint in a method that
4106         // is never reached, but this won't be noticeable to the programmer.
4107         old_method->set_running_emcp(true);
4108         log_trace(redefine, class, iklass, add)
4109           ("EMCP method %s is on_stack " INTPTR_FORMAT, old_method->name_and_sig_as_C_string(), p2i(old_method));
4110       } else if (!old_method->is_obsolete()) {
4111         log_trace(redefine, class, iklass, add)
4112           ("EMCP method %s is NOT on_stack " INTPTR_FORMAT, old_method->name_and_sig_as_C_string(), p2i(old_method));
4113       }
4114     }
4115   }
4116 
4117   // Add previous version if any methods are still running.
4118   // Set has_previous_version flag for processing during class unloading.
4119   _has_previous_versions = true;
4120   log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack.");
4121   assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");
4122   scratch_class->link_previous_versions(previous_versions());
4123   link_previous_versions(scratch_class);
4124 } // end add_previous_version()
4125 
4126 #endif // INCLUDE_JVMTI
4127 
4128 Method* InstanceKlass::method_with_idnum(int idnum) {
4129   Method* m = NULL;
4130   if (idnum < methods()->length()) {
4131     m = methods()->at(idnum);
4132   }
4133   if (m == NULL || m->method_idnum() != idnum) {
4134     for (int index = 0; index < methods()->length(); ++index) {
4135       m = methods()->at(index);
4136       if (m->method_idnum() == idnum) {
4137         return m;
4138       }
4139     }
4140     // None found, return null for the caller to handle.
4141     return NULL;
4142   }
4143   return m;
4144 }
4145 
4146 
4147 Method* InstanceKlass::method_with_orig_idnum(int idnum) {
4148   if (idnum >= methods()->length()) {
4149     return NULL;
4150   }
4151   Method* m = methods()->at(idnum);
4152   if (m != NULL && m->orig_method_idnum() == idnum) {
4153     return m;
4154   }
4155   // Obsolete method idnum does not match the original idnum
4156   for (int index = 0; index < methods()->length(); ++index) {
4157     m = methods()->at(index);
4158     if (m->orig_method_idnum() == idnum) {
4159       return m;
4160     }
4161   }
4162   // None found, return null for the caller to handle.
4163   return NULL;
4164 }
4165 
4166 
4167 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {
4168   InstanceKlass* holder = get_klass_version(version);
4169   if (holder == NULL) {
4170     return NULL; // The version of klass is gone, no method is found
4171   }
4172   Method* method = holder->method_with_orig_idnum(idnum);
4173   return method;
4174 }
4175 
4176 #if INCLUDE_JVMTI
4177 JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() {
4178   return _cached_class_file;
4179 }
4180 
4181 jint InstanceKlass::get_cached_class_file_len() {
4182   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
4183 }
4184 
4185 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
4186   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
4187 }
4188 #endif