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