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