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/klass.inline.hpp"
  68 #include "oops/method.hpp"
  69 #include "oops/oop.inline.hpp"
  70 #include "oops/recordComponent.hpp"
  71 #include "oops/symbol.hpp"

  72 #include "prims/jvmtiExport.hpp"
  73 #include "prims/jvmtiRedefineClasses.hpp"
  74 #include "prims/jvmtiThreadState.hpp"
  75 #include "prims/methodComparator.hpp"
  76 #include "runtime/arguments.hpp"
  77 #include "runtime/atomic.hpp"
  78 #include "runtime/fieldDescriptor.inline.hpp"
  79 #include "runtime/handles.inline.hpp"
  80 #include "runtime/javaCalls.hpp"
  81 #include "runtime/mutexLocker.hpp"
  82 #include "runtime/orderAccess.hpp"
  83 #include "runtime/reflectionUtils.hpp"
  84 #include "runtime/thread.inline.hpp"
  85 #include "services/classLoadingService.hpp"
  86 #include "services/threadService.hpp"
  87 #include "utilities/dtrace.hpp"
  88 #include "utilities/events.hpp"
  89 #include "utilities/macros.hpp"
  90 #include "utilities/stringUtils.hpp"
  91 #include "utilities/pair.hpp"
  92 #ifdef COMPILER1
  93 #include "c1/c1_Compiler.hpp"
  94 #endif
  95 #if INCLUDE_JFR
  96 #include "jfr/jfrEvents.hpp"
  97 #endif
  98 
  99 
 100 #ifdef DTRACE_ENABLED
 101 
 102 
 103 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
 104 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
 105 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
 106 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
 107 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
 108 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
 109 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
 110 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
 111 #define DTRACE_CLASSINIT_PROBE(type, thread_type)                \
 112   {                                                              \
 113     char* data = NULL;                                           \
 114     int len = 0;                                                 \
 115     Symbol* clss_name = name();                                  \
 116     if (clss_name != NULL) {                                     \
 117       data = (char*)clss_name->bytes();                          \
 118       len = clss_name->utf8_length();                            \
 119     }                                                            \
 120     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
 121       data, len, (void*)class_loader(), thread_type);            \
 122   }
 123 
 124 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)     \
 125   {                                                              \
 126     char* data = NULL;                                           \
 127     int len = 0;                                                 \
 128     Symbol* clss_name = name();                                  \
 129     if (clss_name != NULL) {                                     \
 130       data = (char*)clss_name->bytes();                          \
 131       len = clss_name->utf8_length();                            \
 132     }                                                            \
 133     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
 134       data, len, (void*)class_loader(), thread_type, wait);      \
 135   }
 136 
 137 #else //  ndef DTRACE_ENABLED
 138 
 139 #define DTRACE_CLASSINIT_PROBE(type, thread_type)
 140 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)
 141 
 142 #endif //  ndef DTRACE_ENABLED
 143 
 144 
 145 static inline bool is_class_loader(const Symbol* class_name,
 146                                    const ClassFileParser& parser) {
 147   assert(class_name != NULL, "invariant");
 148 
 149   if (class_name == vmSymbols::java_lang_ClassLoader()) {
 150     return true;
 151   }
 152 
 153   if (vmClasses::ClassLoader_klass_loaded()) {
 154     const Klass* const super_klass = parser.super_klass();
 155     if (super_klass != NULL) {
 156       if (super_klass->is_subtype_of(vmClasses::ClassLoader_klass())) {
 157         return true;
 158       }
 159     }
 160   }
 161   return false;
 162 }
 163 


 164 // private: called to verify that k is a static member of this nest.
 165 // We know that k is an instance class in the same package and hence the
 166 // same classloader.
 167 bool InstanceKlass::has_nest_member(JavaThread* current, InstanceKlass* k) const {
 168   assert(!is_hidden(), "unexpected hidden class");
 169   if (_nest_members == NULL || _nest_members == Universe::the_empty_short_array()) {
 170     if (log_is_enabled(Trace, class, nestmates)) {
 171       ResourceMark rm(current);
 172       log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
 173                                   k->external_name(), this->external_name());
 174     }
 175     return false;
 176   }
 177 
 178   if (log_is_enabled(Trace, class, nestmates)) {
 179     ResourceMark rm(current);
 180     log_trace(class, nestmates)("Checking nest membership of %s in %s",
 181                                 k->external_name(), this->external_name());
 182   }
 183 
 184   // Check for the named class in _nest_members.
 185   // We don't resolve, or load, any classes.
 186   for (int i = 0; i < _nest_members->length(); i++) {
 187     int cp_index = _nest_members->at(i);
 188     Symbol* name = _constants->klass_name_at(cp_index);
 189     if (name == k->name()) {
 190       log_trace(class, nestmates)("- named class found at nest_members[%d] => cp[%d]", i, cp_index);
 191       return true;
 192     }
 193   }
 194   log_trace(class, nestmates)("- class is NOT a nest member!");
 195   return false;
 196 }
 197 
 198 // Called to verify that k is a permitted subclass of this class
 199 bool InstanceKlass::has_as_permitted_subclass(const InstanceKlass* k) const {
 200   Thread* current = Thread::current();
 201   assert(k != NULL, "sanity check");
 202   assert(_permitted_subclasses != NULL && _permitted_subclasses != Universe::the_empty_short_array(),
 203          "unexpected empty _permitted_subclasses array");
 204 
 205   if (log_is_enabled(Trace, class, sealed)) {
 206     ResourceMark rm(current);
 207     log_trace(class, sealed)("Checking for permitted subclass of %s in %s",
 208                              k->external_name(), this->external_name());
 209   }
 210 
 211   // Check that the class and its super are in the same module.
 212   if (k->module() != this->module()) {
 213     ResourceMark rm(current);
 214     log_trace(class, sealed)("Check failed for same module of permitted subclass %s and sealed class %s",
 215                              k->external_name(), this->external_name());
 216     return false;
 217   }
 218 
 219   if (!k->is_public() && !is_same_class_package(k)) {
 220     ResourceMark rm(current);
 221     log_trace(class, sealed)("Check failed, subclass %s not public and not in the same package as sealed class %s",
 222                              k->external_name(), this->external_name());
 223     return false;
 224   }
 225 
 226   for (int i = 0; i < _permitted_subclasses->length(); i++) {
 227     int cp_index = _permitted_subclasses->at(i);
 228     Symbol* name = _constants->klass_name_at(cp_index);
 229     if (name == k->name()) {
 230       log_trace(class, sealed)("- Found it at permitted_subclasses[%d] => cp[%d]", i, cp_index);
 231       return true;
 232     }
 233   }
 234   log_trace(class, sealed)("- class is NOT a permitted subclass!");
 235   return false;
 236 }
 237 
 238 // Return nest-host class, resolving, validating and saving it if needed.
 239 // In cases where this is called from a thread that cannot do classloading
 240 // (such as a native JIT thread) then we simply return NULL, which in turn
 241 // causes the access check to return false. Such code will retry the access
 242 // from a more suitable environment later. Otherwise the _nest_host is always
 243 // set once this method returns.
 244 // Any errors from nest-host resolution must be preserved so they can be queried
 245 // from higher-level access checking code, and reported as part of access checking
 246 // exceptions.
 247 // VirtualMachineErrors are propagated with a NULL return.
 248 // Under any conditions where the _nest_host can be set to non-NULL the resulting
 249 // value of it and, if applicable, the nest host resolution/validation error,
 250 // are idempotent.
 251 InstanceKlass* InstanceKlass::nest_host(TRAPS) {
 252   InstanceKlass* nest_host_k = _nest_host;
 253   if (nest_host_k != NULL) {
 254     return nest_host_k;
 255   }
 256 
 257   ResourceMark rm(THREAD);
 258 
 259   // need to resolve and save our nest-host class.
 260   if (_nest_host_index != 0) { // we have a real nest_host
 261     // Before trying to resolve check if we're in a suitable context
 262     bool can_resolve = THREAD->can_call_java();
 263     if (!can_resolve && !_constants->tag_at(_nest_host_index).is_klass()) {
 264       log_trace(class, nestmates)("Rejected resolution of nest-host of %s in unsuitable thread",
 265                                   this->external_name());
 266       return NULL; // sentinel to say "try again from a different context"
 267     }
 268 
 269     log_trace(class, nestmates)("Resolving nest-host of %s using cp entry for %s",
 270                                 this->external_name(),
 271                                 _constants->klass_name_at(_nest_host_index)->as_C_string());
 272 
 273     Klass* k = _constants->klass_at(_nest_host_index, THREAD);
 274     if (HAS_PENDING_EXCEPTION) {
 275       if (PENDING_EXCEPTION->is_a(vmClasses::VirtualMachineError_klass())) {
 276         return NULL; // propagate VMEs
 277       }
 278       stringStream ss;
 279       char* target_host_class = _constants->klass_name_at(_nest_host_index)->as_C_string();
 280       ss.print("Nest host resolution of %s with host %s failed: ",
 281                this->external_name(), target_host_class);
 282       java_lang_Throwable::print(PENDING_EXCEPTION, &ss);
 283       const char* msg = ss.as_string(true /* on C-heap */);
 284       constantPoolHandle cph(THREAD, constants());
 285       SystemDictionary::add_nest_host_error(cph, _nest_host_index, msg);
 286       CLEAR_PENDING_EXCEPTION;
 287 
 288       log_trace(class, nestmates)("%s", msg);
 289     } else {
 290       // A valid nest-host is an instance class in the current package that lists this
 291       // class as a nest member. If any of these conditions are not met the class is
 292       // its own nest-host.
 293       const char* error = NULL;
 294 
 295       // JVMS 5.4.4 indicates package check comes first
 296       if (is_same_class_package(k)) {
 297         // Now check actual membership. We can't be a member if our "host" is
 298         // not an instance class.
 299         if (k->is_instance_klass()) {
 300           nest_host_k = InstanceKlass::cast(k);
 301           bool is_member = nest_host_k->has_nest_member(THREAD, this);
 302           if (is_member) {
 303             _nest_host = nest_host_k; // save resolved nest-host value
 304 
 305             log_trace(class, nestmates)("Resolved nest-host of %s to %s",
 306                                         this->external_name(), k->external_name());
 307             return nest_host_k;
 308           } else {
 309             error = "current type is not listed as a nest member";
 310           }
 311         } else {
 312           error = "host is not an instance class";
 313         }
 314       } else {
 315         error = "types are in different packages";
 316       }
 317 
 318       // something went wrong, so record what and log it
 319       {
 320         stringStream ss;
 321         ss.print("Type %s (loader: %s) is not a nest member of type %s (loader: %s): %s",
 322                  this->external_name(),
 323                  this->class_loader_data()->loader_name_and_id(),
 324                  k->external_name(),
 325                  k->class_loader_data()->loader_name_and_id(),
 326                  error);
 327         const char* msg = ss.as_string(true /* on C-heap */);
 328         constantPoolHandle cph(THREAD, constants());
 329         SystemDictionary::add_nest_host_error(cph, _nest_host_index, msg);
 330         log_trace(class, nestmates)("%s", msg);
 331       }
 332     }
 333   } else {
 334     log_trace(class, nestmates)("Type %s is not part of a nest: setting nest-host to self",
 335                                 this->external_name());
 336   }
 337 
 338   // Either not in an explicit nest, or else an error occurred, so
 339   // the nest-host is set to `this`. Any thread that sees this assignment
 340   // will also see any setting of nest_host_error(), if applicable.
 341   return (_nest_host = this);
 342 }
 343 
 344 // Dynamic nest member support: set this class's nest host to the given class.
 345 // This occurs as part of the class definition, as soon as the instanceKlass
 346 // has been created and doesn't require further resolution. The code:
 347 //    lookup().defineHiddenClass(bytes_for_X, NESTMATE);
 348 // results in:
 349 //    class_of_X.set_nest_host(lookup().lookupClass().getNestHost())
 350 // If it has an explicit _nest_host_index or _nest_members, these will be ignored.
 351 // We also know the "host" is a valid nest-host in the same package so we can
 352 // assert some of those facts.
 353 void InstanceKlass::set_nest_host(InstanceKlass* host) {
 354   assert(is_hidden(), "must be a hidden class");
 355   assert(host != NULL, "NULL nest host specified");
 356   assert(_nest_host == NULL, "current class has resolved nest-host");
 357   assert(nest_host_error() == NULL, "unexpected nest host resolution error exists: %s",
 358          nest_host_error());
 359   assert((host->_nest_host == NULL && host->_nest_host_index == 0) ||
 360          (host->_nest_host == host), "proposed host is not a valid nest-host");
 361   // Can't assert this as package is not set yet:
 362   // assert(is_same_class_package(host), "proposed host is in wrong package");
 363 
 364   if (log_is_enabled(Trace, class, nestmates)) {
 365     ResourceMark rm;
 366     const char* msg = "";
 367     // a hidden class does not expect a statically defined nest-host
 368     if (_nest_host_index > 0) {
 369       msg = "(the NestHost attribute in the current class is ignored)";
 370     } else if (_nest_members != NULL && _nest_members != Universe::the_empty_short_array()) {
 371       msg = "(the NestMembers attribute in the current class is ignored)";
 372     }
 373     log_trace(class, nestmates)("Injected type %s into the nest of %s %s",
 374                                 this->external_name(),
 375                                 host->external_name(),
 376                                 msg);
 377   }
 378   // set dynamic nest host
 379   _nest_host = host;
 380   // Record dependency to keep nest host from being unloaded before this class.
 381   ClassLoaderData* this_key = class_loader_data();
 382   this_key->record_dependency(host);
 383 }
 384 
 385 // check if 'this' and k are nestmates (same nest_host), or k is our nest_host,
 386 // or we are k's nest_host - all of which is covered by comparing the two
 387 // resolved_nest_hosts.
 388 // Any exceptions (i.e. VMEs) are propagated.
 389 bool InstanceKlass::has_nestmate_access_to(InstanceKlass* k, TRAPS) {
 390 
 391   assert(this != k, "this should be handled by higher-level code");
 392 
 393   // Per JVMS 5.4.4 we first resolve and validate the current class, then
 394   // the target class k.
 395 
 396   InstanceKlass* cur_host = nest_host(CHECK_false);
 397   if (cur_host == NULL) {
 398     return false;
 399   }
 400 
 401   Klass* k_nest_host = k->nest_host(CHECK_false);
 402   if (k_nest_host == NULL) {
 403     return false;
 404   }
 405 
 406   bool access = (cur_host == k_nest_host);
 407 
 408   ResourceMark rm(THREAD);
 409   log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
 410                               this->external_name(),
 411                               access ? "" : "NOT ",
 412                               k->external_name());
 413   return access;
 414 }
 415 
 416 const char* InstanceKlass::nest_host_error() {
 417   if (_nest_host_index == 0) {
 418     return NULL;
 419   } else {
 420     constantPoolHandle cph(Thread::current(), constants());
 421     return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index);
 422   }
 423 }
 424 
 425 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
 426   const int size = InstanceKlass::size(parser.vtable_size(),
 427                                        parser.itable_size(),
 428                                        nonstatic_oop_map_size(parser.total_oop_map_count()),
 429                                        parser.is_interface());


 430 
 431   const Symbol* const class_name = parser.class_name();
 432   assert(class_name != NULL, "invariant");
 433   ClassLoaderData* loader_data = parser.loader_data();
 434   assert(loader_data != NULL, "invariant");
 435 
 436   InstanceKlass* ik;
 437 
 438   // Allocation
 439   if (REF_NONE == parser.reference_type()) {
 440     if (class_name == vmSymbols::java_lang_Class()) {
 441       // mirror
 442       ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
 443     }
 444     else if (is_class_loader(class_name, parser)) {
 445       // class loader
 446       ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);



 447     } else {
 448       // normal
 449       ik = new (loader_data, size, THREAD) InstanceKlass(parser, InstanceKlass::_kind_other);
 450     }
 451   } else {
 452     // reference
 453     ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
 454   }
 455 
 456   // Check for pending exception before adding to the loader data and incrementing
 457   // class count.  Can get OOM here.
 458   if (HAS_PENDING_EXCEPTION) {
 459     return NULL;
 460   }
 461 







 462   return ik;
 463 }
 464 























 465 
 466 // copy method ordering from resource area to Metaspace
 467 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
 468   if (m != NULL) {
 469     // allocate a new array and copy contents (memcpy?)
 470     _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
 471     for (int i = 0; i < m->length(); i++) {
 472       _method_ordering->at_put(i, m->at(i));
 473     }
 474   } else {
 475     _method_ordering = Universe::the_empty_int_array();
 476   }
 477 }
 478 
 479 // create a new array of vtable_indices for default methods
 480 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
 481   Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
 482   assert(default_vtable_indices() == NULL, "only create once");
 483   set_default_vtable_indices(vtable_indices);
 484   return vtable_indices;
 485 }
 486 
 487 InstanceKlass::InstanceKlass(const ClassFileParser& parser, unsigned kind, KlassID id) :
 488   Klass(id),
 489   _nest_members(NULL),
 490   _nest_host(NULL),
 491   _permitted_subclasses(NULL),
 492   _record_components(NULL),
 493   _static_field_size(parser.static_field_size()),
 494   _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
 495   _itable_len(parser.itable_size()),
 496   _nest_host_index(0),
 497   _init_state(allocated),
 498   _reference_type(parser.reference_type()),
 499   _init_thread(NULL)


 500 {
 501   set_vtable_length(parser.vtable_size());
 502   set_kind(kind);
 503   set_access_flags(parser.access_flags());
 504   if (parser.is_hidden()) set_is_hidden();
 505   set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
 506                                                     false));




 507 
 508   assert(NULL == _methods, "underlying memory not zeroed?");
 509   assert(is_instance_klass(), "is layout incorrect?");
 510   assert(size_helper() == parser.layout_size(), "incorrect size_helper?");




 511 }
 512 
 513 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
 514                                        Array<Method*>* methods) {
 515   if (methods != NULL && methods != Universe::the_empty_method_array() &&
 516       !methods->is_shared()) {
 517     for (int i = 0; i < methods->length(); i++) {
 518       Method* method = methods->at(i);
 519       if (method == NULL) continue;  // maybe null if error processing
 520       // Only want to delete methods that are not executing for RedefineClasses.
 521       // The previous version will point to them so they're not totally dangling
 522       assert (!method->on_stack(), "shouldn't be called with methods on stack");
 523       MetadataFactory::free_metadata(loader_data, method);
 524     }
 525     MetadataFactory::free_array<Method*>(loader_data, methods);
 526   }
 527 }
 528 
 529 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
 530                                           const Klass* super_klass,
 531                                           Array<InstanceKlass*>* local_interfaces,
 532                                           Array<InstanceKlass*>* transitive_interfaces) {
 533   // Only deallocate transitive interfaces if not empty, same as super class
 534   // or same as local interfaces.  See code in parseClassFile.
 535   Array<InstanceKlass*>* ti = transitive_interfaces;
 536   if (ti != Universe::the_empty_instance_klass_array() && ti != local_interfaces) {
 537     // check that the interfaces don't come from super class
 538     Array<InstanceKlass*>* sti = (super_klass == NULL) ? NULL :
 539                     InstanceKlass::cast(super_klass)->transitive_interfaces();
 540     if (ti != sti && ti != NULL && !ti->is_shared()) {


 541       MetadataFactory::free_array<InstanceKlass*>(loader_data, ti);
 542     }
 543   }
 544 
 545   // local interfaces can be empty
 546   if (local_interfaces != Universe::the_empty_instance_klass_array() &&
 547       local_interfaces != NULL && !local_interfaces->is_shared()) {


 548     MetadataFactory::free_array<InstanceKlass*>(loader_data, local_interfaces);
 549   }
 550 }
 551 
 552 void InstanceKlass::deallocate_record_components(ClassLoaderData* loader_data,
 553                                                  Array<RecordComponent*>* record_components) {
 554   if (record_components != NULL && !record_components->is_shared()) {
 555     for (int i = 0; i < record_components->length(); i++) {
 556       RecordComponent* record_component = record_components->at(i);
 557       MetadataFactory::free_metadata(loader_data, record_component);
 558     }
 559     MetadataFactory::free_array<RecordComponent*>(loader_data, record_components);
 560   }
 561 }
 562 
 563 // This function deallocates the metadata and C heap pointers that the
 564 // InstanceKlass points to.
 565 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
 566 
 567   // Orphan the mirror first, CMS thinks it's still live.
 568   if (java_mirror() != NULL) {
 569     java_lang_Class::set_klass(java_mirror(), NULL);
 570   }
 571 
 572   // Also remove mirror from handles
 573   loader_data->remove_handle(_java_mirror);
 574 
 575   // Need to take this class off the class loader data list.
 576   loader_data->remove_class(this);
 577 
 578   // The array_klass for this class is created later, after error handling.
 579   // For class redefinition, we keep the original class so this scratch class
 580   // doesn't have an array class.  Either way, assert that there is nothing
 581   // to deallocate.
 582   assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
 583 
 584   // Release C heap allocated data that this points to, which includes
 585   // reference counting symbol names.
 586   release_C_heap_structures_internal();
 587 
 588   deallocate_methods(loader_data, methods());
 589   set_methods(NULL);
 590 
 591   deallocate_record_components(loader_data, record_components());
 592   set_record_components(NULL);
 593 
 594   if (method_ordering() != NULL &&
 595       method_ordering() != Universe::the_empty_int_array() &&
 596       !method_ordering()->is_shared()) {
 597     MetadataFactory::free_array<int>(loader_data, method_ordering());
 598   }
 599   set_method_ordering(NULL);
 600 
 601   // default methods can be empty
 602   if (default_methods() != NULL &&
 603       default_methods() != Universe::the_empty_method_array() &&
 604       !default_methods()->is_shared()) {
 605     MetadataFactory::free_array<Method*>(loader_data, default_methods());
 606   }
 607   // Do NOT deallocate the default methods, they are owned by superinterfaces.
 608   set_default_methods(NULL);
 609 
 610   // default methods vtable indices can be empty
 611   if (default_vtable_indices() != NULL &&
 612       !default_vtable_indices()->is_shared()) {
 613     MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
 614   }
 615   set_default_vtable_indices(NULL);
 616 
 617 
 618   // This array is in Klass, but remove it with the InstanceKlass since
 619   // this place would be the only caller and it can share memory with transitive
 620   // interfaces.
 621   if (secondary_supers() != NULL &&
 622       secondary_supers() != Universe::the_empty_klass_array() &&
 623       // see comments in compute_secondary_supers about the following cast
 624       (address)(secondary_supers()) != (address)(transitive_interfaces()) &&
 625       !secondary_supers()->is_shared()) {
 626     MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
 627   }
 628   set_secondary_supers(NULL);
 629 
 630   deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
 631   set_transitive_interfaces(NULL);
 632   set_local_interfaces(NULL);
 633 
 634   if (fields() != NULL && !fields()->is_shared()) {
 635     MetadataFactory::free_array<jushort>(loader_data, fields());
 636   }
 637   set_fields(NULL, 0);
 638 
 639   // If a method from a redefined class is using this constant pool, don't
 640   // delete it, yet.  The new class's previous version will point to this.
 641   if (constants() != NULL) {
 642     assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
 643     if (!constants()->is_shared()) {
 644       MetadataFactory::free_metadata(loader_data, constants());
 645     }
 646     // Delete any cached resolution errors for the constant pool
 647     SystemDictionary::delete_resolution_error(constants());
 648 
 649     set_constants(NULL);
 650   }
 651 
 652   if (inner_classes() != NULL &&
 653       inner_classes() != Universe::the_empty_short_array() &&
 654       !inner_classes()->is_shared()) {
 655     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
 656   }
 657   set_inner_classes(NULL);
 658 
 659   if (nest_members() != NULL &&
 660       nest_members() != Universe::the_empty_short_array() &&
 661       !nest_members()->is_shared()) {
 662     MetadataFactory::free_array<jushort>(loader_data, nest_members());
 663   }
 664   set_nest_members(NULL);
 665 
 666   if (permitted_subclasses() != NULL &&
 667       permitted_subclasses() != Universe::the_empty_short_array() &&
 668       !permitted_subclasses()->is_shared()) {
 669     MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
 670   }
 671   set_permitted_subclasses(NULL);
 672 
 673   // We should deallocate the Annotations instance if it's not in shared spaces.
 674   if (annotations() != NULL && !annotations()->is_shared()) {
 675     MetadataFactory::free_metadata(loader_data, annotations());
 676   }
 677   set_annotations(NULL);
 678 
 679   SystemDictionaryShared::handle_class_unloading(this);
 680 }
 681 
 682 bool InstanceKlass::is_record() const {
 683   return _record_components != NULL &&
 684          is_final() &&
 685          java_super() == vmClasses::Record_klass();
 686 }
 687 
 688 bool InstanceKlass::is_sealed() const {
 689   return _permitted_subclasses != NULL &&
 690          _permitted_subclasses != Universe::the_empty_short_array();
 691 }
 692 
 693 bool InstanceKlass::should_be_initialized() const {
 694   return !is_initialized();
 695 }
 696 
 697 klassItable InstanceKlass::itable() const {
 698   return klassItable(const_cast<InstanceKlass*>(this));
 699 }
 700 
 701 void InstanceKlass::eager_initialize(Thread *thread) {
 702   if (!EagerInitialization) return;
 703 
 704   if (this->is_not_initialized()) {
 705     // abort if the the class has a class initializer
 706     if (this->class_initializer() != NULL) return;
 707 
 708     // abort if it is java.lang.Object (initialization is handled in genesis)
 709     Klass* super_klass = super();
 710     if (super_klass == NULL) return;
 711 
 712     // abort if the super class should be initialized
 713     if (!InstanceKlass::cast(super_klass)->is_initialized()) return;
 714 
 715     // call body to expose the this pointer
 716     eager_initialize_impl();
 717   }
 718 }
 719 
 720 // JVMTI spec thinks there are signers and protection domain in the
 721 // instanceKlass.  These accessors pretend these fields are there.
 722 // The hprof specification also thinks these fields are in InstanceKlass.
 723 oop InstanceKlass::protection_domain() const {
 724   // return the protection_domain from the mirror
 725   return java_lang_Class::protection_domain(java_mirror());
 726 }
 727 
 728 // To remove these from requires an incompatible change and CCC request.
 729 objArrayOop InstanceKlass::signers() const {
 730   // return the signers from the mirror
 731   return java_lang_Class::signers(java_mirror());
 732 }
 733 
 734 oop InstanceKlass::init_lock() const {
 735   // return the init lock from the mirror
 736   oop lock = java_lang_Class::init_lock(java_mirror());
 737   // Prevent reordering with any access of initialization state
 738   OrderAccess::loadload();
 739   assert(lock != NULL || !is_not_initialized(), // initialized or in_error state
 740          "only fully initialized state can have a null lock");
 741   return lock;
 742 }
 743 
 744 // Set the initialization lock to null so the object can be GC'ed.  Any racing
 745 // threads to get this lock will see a null lock and will not lock.
 746 // That's okay because they all check for initialized state after getting
 747 // the lock and return.
 748 void InstanceKlass::fence_and_clear_init_lock() {
 749   // make sure previous stores are all done, notably the init_state.
 750   OrderAccess::storestore();
 751   java_lang_Class::clear_init_lock(java_mirror());
 752   assert(!is_not_initialized(), "class must be initialized now");
 753 }
 754 
 755 void InstanceKlass::eager_initialize_impl() {
 756   EXCEPTION_MARK;
 757   HandleMark hm(THREAD);
 758   Handle h_init_lock(THREAD, init_lock());
 759   ObjectLocker ol(h_init_lock, THREAD);
 760 
 761   // abort if someone beat us to the initialization
 762   if (!is_not_initialized()) return;  // note: not equivalent to is_initialized()
 763 
 764   ClassState old_state = init_state();
 765   link_class_impl(THREAD);
 766   if (HAS_PENDING_EXCEPTION) {
 767     CLEAR_PENDING_EXCEPTION;
 768     // Abort if linking the class throws an exception.
 769 
 770     // Use a test to avoid redundantly resetting the state if there's
 771     // no change.  Set_init_state() asserts that state changes make
 772     // progress, whereas here we might just be spinning in place.
 773     if (old_state != _init_state)
 774       set_init_state(old_state);
 775   } else {
 776     // linking successfull, mark class as initialized
 777     set_init_state(fully_initialized);
 778     fence_and_clear_init_lock();
 779     // trace
 780     if (log_is_enabled(Info, class, init)) {
 781       ResourceMark rm(THREAD);
 782       log_info(class, init)("[Initialized %s without side effects]", external_name());
 783     }
 784   }
 785 }
 786 
 787 
 788 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
 789 // process. The step comments refers to the procedure described in that section.
 790 // Note: implementation moved to static method to expose the this pointer.
 791 void InstanceKlass::initialize(TRAPS) {
 792   if (this->should_be_initialized()) {
 793     initialize_impl(CHECK);
 794     // Note: at this point the class may be initialized
 795     //       OR it may be in the state of being initialized
 796     //       in case of recursive initialization!
 797   } else {
 798     assert(is_initialized(), "sanity check");
 799   }
 800 }
 801 
 802 
 803 bool InstanceKlass::verify_code(TRAPS) {
 804   // 1) Verify the bytecodes
 805   return Verifier::verify(this, should_verify_class(), THREAD);
 806 }
 807 
 808 void InstanceKlass::link_class(TRAPS) {
 809   assert(is_loaded(), "must be loaded");
 810   if (!is_linked()) {
 811     link_class_impl(CHECK);
 812   }
 813 }
 814 
 815 // Called to verify that a class can link during initialization, without
 816 // throwing a VerifyError.
 817 bool InstanceKlass::link_class_or_fail(TRAPS) {
 818   assert(is_loaded(), "must be loaded");
 819   if (!is_linked()) {
 820     link_class_impl(CHECK_false);
 821   }
 822   return is_linked();
 823 }
 824 
 825 bool InstanceKlass::link_class_impl(TRAPS) {
 826   if (DumpSharedSpaces && SystemDictionaryShared::has_class_failed_verification(this)) {
 827     // This is for CDS dumping phase only -- we use the in_error_state to indicate that
 828     // the class has failed verification. Throwing the NoClassDefFoundError here is just
 829     // a convenient way to stop repeat attempts to verify the same (bad) class.
 830     //
 831     // Note that the NoClassDefFoundError is not part of the JLS, and should not be thrown
 832     // if we are executing Java code. This is not a problem for CDS dumping phase since
 833     // it doesn't execute any Java code.
 834     ResourceMark rm(THREAD);
 835     Exceptions::fthrow(THREAD_AND_LOCATION,
 836                        vmSymbols::java_lang_NoClassDefFoundError(),
 837                        "Class %s, or one of its supertypes, failed class initialization",
 838                        external_name());
 839     return false;
 840   }
 841   // return if already verified
 842   if (is_linked()) {
 843     return true;
 844   }
 845 
 846   // Timing
 847   // timer handles recursion
 848   JavaThread* jt = THREAD;
 849 
 850   // link super class before linking this class
 851   Klass* super_klass = super();
 852   if (super_klass != NULL) {
 853     if (super_klass->is_interface()) {  // check if super class is an interface
 854       ResourceMark rm(THREAD);
 855       Exceptions::fthrow(
 856         THREAD_AND_LOCATION,
 857         vmSymbols::java_lang_IncompatibleClassChangeError(),
 858         "class %s has interface %s as super class",
 859         external_name(),
 860         super_klass->external_name()
 861       );
 862       return false;
 863     }
 864 
 865     InstanceKlass* ik_super = InstanceKlass::cast(super_klass);
 866     ik_super->link_class_impl(CHECK_false);
 867   }
 868 
 869   // link all interfaces implemented by this class before linking this class
 870   Array<InstanceKlass*>* interfaces = local_interfaces();
 871   int num_interfaces = interfaces->length();
 872   for (int index = 0; index < num_interfaces; index++) {
 873     InstanceKlass* interk = interfaces->at(index);
 874     interk->link_class_impl(CHECK_false);
 875   }
 876 
























































 877   // in case the class is linked in the process of linking its superclasses
 878   if (is_linked()) {
 879     return true;
 880   }
 881 
 882   // trace only the link time for this klass that includes
 883   // the verification time
 884   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
 885                              ClassLoader::perf_class_link_selftime(),
 886                              ClassLoader::perf_classes_linked(),
 887                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 888                              jt->get_thread_stat()->perf_timers_addr(),
 889                              PerfClassTraceTime::CLASS_LINK);
 890 
 891   // verification & rewriting
 892   {
 893     HandleMark hm(THREAD);
 894     Handle h_init_lock(THREAD, init_lock());
 895     ObjectLocker ol(h_init_lock, jt);
 896     // rewritten will have been set if loader constraint error found
 897     // on an earlier link attempt
 898     // don't verify or rewrite if already rewritten
 899     //
 900 
 901     if (!is_linked()) {
 902       if (!is_rewritten()) {
 903         if (is_shared()) {
 904           assert(!verified_at_dump_time(), "must be");
 905         }
 906         {
 907           bool verify_ok = verify_code(THREAD);
 908           if (!verify_ok) {
 909             return false;
 910           }
 911         }
 912 
 913         // Just in case a side-effect of verify linked this class already
 914         // (which can sometimes happen since the verifier loads classes
 915         // using custom class loaders, which are free to initialize things)
 916         if (is_linked()) {
 917           return true;
 918         }
 919 
 920         // also sets rewritten
 921         rewrite_class(CHECK_false);
 922       } else if (is_shared()) {
 923         SystemDictionaryShared::check_verification_constraints(this, CHECK_false);
 924       }
 925 
 926       // relocate jsrs and link methods after they are all rewritten
 927       link_methods(CHECK_false);
 928 
 929       // Initialize the vtable and interface table after
 930       // methods have been rewritten since rewrite may
 931       // fabricate new Method*s.
 932       // also does loader constraint checking
 933       //
 934       // initialize_vtable and initialize_itable need to be rerun
 935       // for a shared class if
 936       // 1) the class is loaded by custom class loader or
 937       // 2) the class is loaded by built-in class loader but failed to add archived loader constraints or
 938       // 3) the class was not verified during dump time
 939       bool need_init_table = true;
 940       if (is_shared() && verified_at_dump_time() &&
 941           SystemDictionaryShared::check_linking_constraints(THREAD, this)) {
 942         need_init_table = false;
 943       }
 944       if (need_init_table) {
 945         vtable().initialize_vtable_and_check_constraints(CHECK_false);
 946         itable().initialize_itable_and_check_constraints(CHECK_false);
 947       }
 948 #ifdef ASSERT
 949       vtable().verify(tty, true);
 950       // In case itable verification is ever added.
 951       // itable().verify(tty, true);
 952 #endif
 953       if (UseVtableBasedCHA) {
 954         MutexLocker ml(THREAD, Compile_lock);
 955         set_init_state(linked);
 956 
 957         // Now flush all code that assume the class is not linked.
 958         if (Universe::is_fully_initialized()) {
 959           CodeCache::flush_dependents_on(this);
 960         }
 961       } else {
 962         set_init_state(linked);
 963       }
 964       if (JvmtiExport::should_post_class_prepare()) {
 965         JvmtiExport::post_class_prepare(THREAD, this);
 966       }
 967     }
 968   }
 969   return true;
 970 }
 971 
 972 // Rewrite the byte codes of all of the methods of a class.
 973 // The rewriter must be called exactly once. Rewriting must happen after
 974 // verification but before the first method of the class is executed.
 975 void InstanceKlass::rewrite_class(TRAPS) {
 976   assert(is_loaded(), "must be loaded");
 977   if (is_rewritten()) {
 978     assert(is_shared(), "rewriting an unshared class?");
 979     return;
 980   }
 981   Rewriter::rewrite(this, CHECK);
 982   set_rewritten();
 983 }
 984 
 985 // Now relocate and link method entry points after class is rewritten.
 986 // This is outside is_rewritten flag. In case of an exception, it can be
 987 // executed more than once.
 988 void InstanceKlass::link_methods(TRAPS) {
 989   int len = methods()->length();
 990   for (int i = len-1; i >= 0; i--) {
 991     methodHandle m(THREAD, methods()->at(i));
 992 
 993     // Set up method entry points for compiler and interpreter    .
 994     m->link_method(m, CHECK);
 995   }
 996 }
 997 
 998 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
 999 void InstanceKlass::initialize_super_interfaces(TRAPS) {
1000   assert (has_nonstatic_concrete_methods(), "caller should have checked this");
1001   for (int i = 0; i < local_interfaces()->length(); ++i) {
1002     InstanceKlass* ik = local_interfaces()->at(i);
1003 
1004     // Initialization is depth first search ie. we start with top of the inheritance tree
1005     // has_nonstatic_concrete_methods drives searching superinterfaces since it
1006     // means has_nonstatic_concrete_methods in its superinterface hierarchy
1007     if (ik->has_nonstatic_concrete_methods()) {
1008       ik->initialize_super_interfaces(CHECK);
1009     }
1010 
1011     // Only initialize() interfaces that "declare" concrete methods.
1012     if (ik->should_be_initialized() && ik->declares_nonstatic_concrete_methods()) {
1013       ik->initialize(CHECK);
1014     }
1015   }
1016 }
1017 
1018 ResourceHashtable<const InstanceKlass*, OopHandle, 107, ResourceObj::C_HEAP, mtClass>
1019       _initialization_error_table;
1020 
1021 void InstanceKlass::add_initialization_error(JavaThread* current, Handle exception) {
1022   // Create the same exception with a message indicating the thread name,
1023   // and the StackTraceElements.
1024   // If the initialization error is OOM, this might not work, but if GC kicks in
1025   // this would be still be helpful.
1026   JavaThread* THREAD = current;
1027   Handle cause = java_lang_Throwable::get_cause_with_stack_trace(exception, THREAD);
1028   if (HAS_PENDING_EXCEPTION || cause.is_null()) {
1029     CLEAR_PENDING_EXCEPTION;
1030     return;
1031   }
1032 
1033   MutexLocker ml(THREAD, ClassInitError_lock);
1034   OopHandle elem = OopHandle(Universe::vm_global(), cause());
1035   bool created = false;
1036   _initialization_error_table.put_if_absent(this, elem, &created);
1037   assert(created, "Initialization is single threaded");
1038   ResourceMark rm(THREAD);
1039   log_trace(class, init)("Initialization error added for class %s", external_name());
1040 }
1041 
1042 oop InstanceKlass::get_initialization_error(JavaThread* current) {
1043   MutexLocker ml(current, ClassInitError_lock);
1044   OopHandle* h = _initialization_error_table.get(this);
1045   return (h != nullptr) ? h->resolve() : nullptr;
1046 }
1047 
1048 // Need to remove entries for unloaded classes.
1049 void InstanceKlass::clean_initialization_error_table() {
1050   struct InitErrorTableCleaner {
1051     bool do_entry(const InstanceKlass* ik, OopHandle h) {
1052       if (!ik->is_loader_alive()) {
1053         h.release(Universe::vm_global());
1054         return true;
1055       } else {
1056         return false;
1057       }
1058     }
1059   };
1060 
1061   MutexLocker ml(ClassInitError_lock);
1062   InitErrorTableCleaner cleaner;
1063   _initialization_error_table.unlink(&cleaner);
1064 }
1065 
1066 void InstanceKlass::initialize_impl(TRAPS) {
1067   HandleMark hm(THREAD);
1068 
1069   // Make sure klass is linked (verified) before initialization
1070   // A class could already be verified, since it has been reflected upon.
1071   link_class(CHECK);
1072 
1073   DTRACE_CLASSINIT_PROBE(required, -1);
1074 
1075   bool wait = false;
1076 
1077   JavaThread* jt = THREAD;
1078 
1079   // refer to the JVM book page 47 for description of steps
1080   // Step 1
1081   {
1082     Handle h_init_lock(THREAD, init_lock());
1083     ObjectLocker ol(h_init_lock, jt);
1084 
1085     // Step 2
1086     // If we were to use wait() instead of waitInterruptibly() then
1087     // we might end up throwing IE from link/symbol resolution sites
1088     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
1089     while (is_being_initialized() && !is_reentrant_initialization(jt)) {
1090       wait = true;
1091       jt->set_class_to_be_initialized(this);
1092       ol.wait_uninterruptibly(jt);
1093       jt->set_class_to_be_initialized(NULL);
1094     }
1095 
1096     // Step 3
1097     if (is_being_initialized() && is_reentrant_initialization(jt)) {
1098       DTRACE_CLASSINIT_PROBE_WAIT(recursive, -1, wait);
1099       return;
1100     }
1101 
1102     // Step 4
1103     if (is_initialized()) {
1104       DTRACE_CLASSINIT_PROBE_WAIT(concurrent, -1, wait);
1105       return;
1106     }
1107 
1108     // Step 5
1109     if (is_in_error_state()) {
1110       DTRACE_CLASSINIT_PROBE_WAIT(erroneous, -1, wait);
1111       ResourceMark rm(THREAD);
1112       Handle cause(THREAD, get_initialization_error(THREAD));
1113 
1114       stringStream ss;
1115       ss.print("Could not initialize class %s", external_name());
1116       if (cause.is_null()) {
1117         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), ss.as_string());
1118       } else {
1119         THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1120                         ss.as_string(), cause);
1121       }
1122     }
1123 
1124     // Step 6
1125     set_init_state(being_initialized);
1126     set_init_thread(jt);
1127   }
1128 



















1129   // Step 7
1130   // Next, if C is a class rather than an interface, initialize it's super class and super
1131   // interfaces.
1132   if (!is_interface()) {
1133     Klass* super_klass = super();
1134     if (super_klass != NULL && super_klass->should_be_initialized()) {
1135       super_klass->initialize(THREAD);
1136     }
1137     // If C implements any interface that declares a non-static, concrete method,
1138     // the initialization of C triggers initialization of its super interfaces.
1139     // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1140     // having a superinterface that declares, non-static, concrete methods
1141     if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1142       initialize_super_interfaces(THREAD);
1143     }
1144 
1145     // If any exceptions, complete abruptly, throwing the same exception as above.
1146     if (HAS_PENDING_EXCEPTION) {
1147       Handle e(THREAD, PENDING_EXCEPTION);
1148       CLEAR_PENDING_EXCEPTION;
1149       {
1150         EXCEPTION_MARK;
1151         add_initialization_error(THREAD, e);
1152         // Locks object, set state, and notify all waiting threads
1153         set_initialization_state_and_notify(initialization_error, THREAD);
1154         CLEAR_PENDING_EXCEPTION;
1155       }
1156       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1157       THROW_OOP(e());
1158     }
1159   }
1160 
1161 
1162   // Step 8









































1163   {
1164     DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1165     if (class_initializer() != NULL) {
1166       // Timer includes any side effects of class initialization (resolution,
1167       // etc), but not recursive entry into call_class_initializer().
1168       PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1169                                ClassLoader::perf_class_init_selftime(),
1170                                ClassLoader::perf_classes_inited(),
1171                                jt->get_thread_stat()->perf_recursion_counts_addr(),
1172                                jt->get_thread_stat()->perf_timers_addr(),
1173                                PerfClassTraceTime::CLASS_CLINIT);
1174       call_class_initializer(THREAD);
1175     } else {
1176       // The elapsed time is so small it's not worth counting.
1177       if (UsePerfData) {
1178         ClassLoader::perf_classes_inited()->inc();
1179       }
1180       call_class_initializer(THREAD);
1181     }
1182   }
1183 
1184   // Step 9
1185   if (!HAS_PENDING_EXCEPTION) {
1186     set_initialization_state_and_notify(fully_initialized, CHECK);
1187     debug_only(vtable().verify(tty, true);)
1188   }
1189   else {
1190     // Step 10 and 11
1191     Handle e(THREAD, PENDING_EXCEPTION);
1192     CLEAR_PENDING_EXCEPTION;
1193     // JVMTI has already reported the pending exception
1194     // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1195     JvmtiExport::clear_detected_exception(jt);
1196     {
1197       EXCEPTION_MARK;
1198       add_initialization_error(THREAD, e);
1199       set_initialization_state_and_notify(initialization_error, THREAD);
1200       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
1201       // JVMTI has already reported the pending exception
1202       // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1203       JvmtiExport::clear_detected_exception(jt);
1204     }
1205     DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1206     if (e->is_a(vmClasses::Error_klass())) {
1207       THROW_OOP(e());
1208     } else {
1209       JavaCallArguments args(e);
1210       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
1211                 vmSymbols::throwable_void_signature(),
1212                 &args);
1213     }
1214   }
1215   DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1216 }
1217 
1218 
1219 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1220   Handle h_init_lock(THREAD, init_lock());
1221   if (h_init_lock() != NULL) {
1222     ObjectLocker ol(h_init_lock, THREAD);
1223     set_init_thread(NULL); // reset _init_thread before changing _init_state
1224     set_init_state(state);
1225     fence_and_clear_init_lock();
1226     ol.notify_all(CHECK);
1227   } else {
1228     assert(h_init_lock() != NULL, "The initialization state should never be set twice");
1229     set_init_thread(NULL); // reset _init_thread before changing _init_state
1230     set_init_state(state);
1231   }
1232 }
1233 
1234 InstanceKlass* InstanceKlass::implementor() const {
1235   InstanceKlass* volatile* ik = adr_implementor();
1236   if (ik == NULL) {
1237     return NULL;
1238   } else {
1239     // This load races with inserts, and therefore needs acquire.
1240     InstanceKlass* ikls = Atomic::load_acquire(ik);
1241     if (ikls != NULL && !ikls->is_loader_alive()) {
1242       return NULL;  // don't return unloaded class
1243     } else {
1244       return ikls;
1245     }
1246   }
1247 }
1248 
1249 
1250 void InstanceKlass::set_implementor(InstanceKlass* ik) {
1251   assert_locked_or_safepoint(Compile_lock);
1252   assert(is_interface(), "not interface");
1253   InstanceKlass* volatile* addr = adr_implementor();
1254   assert(addr != NULL, "null addr");
1255   if (addr != NULL) {
1256     Atomic::release_store(addr, ik);
1257   }
1258 }
1259 
1260 int  InstanceKlass::nof_implementors() const {
1261   InstanceKlass* ik = implementor();
1262   if (ik == NULL) {
1263     return 0;
1264   } else if (ik != this) {
1265     return 1;
1266   } else {
1267     return 2;
1268   }
1269 }
1270 
1271 // The embedded _implementor field can only record one implementor.
1272 // When there are more than one implementors, the _implementor field
1273 // is set to the interface Klass* itself. Following are the possible
1274 // values for the _implementor field:
1275 //   NULL                  - no implementor
1276 //   implementor Klass*    - one implementor
1277 //   self                  - more than one implementor
1278 //
1279 // The _implementor field only exists for interfaces.
1280 void InstanceKlass::add_implementor(InstanceKlass* ik) {
1281   if (Universe::is_fully_initialized()) {
1282     assert_lock_strong(Compile_lock);
1283   }
1284   assert(is_interface(), "not interface");
1285   // Filter out my subinterfaces.
1286   // (Note: Interfaces are never on the subklass list.)
1287   if (ik->is_interface()) return;
1288 
1289   // Filter out subclasses whose supers already implement me.
1290   // (Note: CHA must walk subclasses of direct implementors
1291   // in order to locate indirect implementors.)
1292   InstanceKlass* super_ik = ik->java_super();
1293   if (super_ik != NULL && super_ik->implements_interface(this))
1294     // We only need to check one immediate superclass, since the
1295     // implements_interface query looks at transitive_interfaces.
1296     // Any supers of the super have the same (or fewer) transitive_interfaces.
1297     return;
1298 
1299   InstanceKlass* iklass = implementor();
1300   if (iklass == NULL) {
1301     set_implementor(ik);
1302   } else if (iklass != this && iklass != ik) {
1303     // There is already an implementor. Use itself as an indicator of
1304     // more than one implementors.
1305     set_implementor(this);
1306   }
1307 
1308   // The implementor also implements the transitive_interfaces
1309   for (int index = 0; index < local_interfaces()->length(); index++) {
1310     local_interfaces()->at(index)->add_implementor(ik);
1311   }
1312 }
1313 
1314 void InstanceKlass::init_implementor() {
1315   if (is_interface()) {
1316     set_implementor(NULL);
1317   }
1318 }
1319 
1320 
1321 void InstanceKlass::process_interfaces() {
1322   // link this class into the implementors list of every interface it implements
1323   for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
1324     assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
1325     InstanceKlass* interf = local_interfaces()->at(i);
1326     assert(interf->is_interface(), "expected interface");
1327     interf->add_implementor(this);
1328   }
1329 }
1330 
1331 bool InstanceKlass::can_be_primary_super_slow() const {
1332   if (is_interface())
1333     return false;
1334   else
1335     return Klass::can_be_primary_super_slow();
1336 }
1337 
1338 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots,
1339                                                                Array<InstanceKlass*>* transitive_interfaces) {
1340   // The secondaries are the implemented interfaces.
1341   Array<InstanceKlass*>* interfaces = transitive_interfaces;
1342   int num_secondaries = num_extra_slots + interfaces->length();
1343   if (num_secondaries == 0) {
1344     // Must share this for correct bootstrapping!
1345     set_secondary_supers(Universe::the_empty_klass_array());
1346     return NULL;
1347   } else if (num_extra_slots == 0) {
1348     // The secondary super list is exactly the same as the transitive interfaces, so
1349     // let's use it instead of making a copy.
1350     // Redefine classes has to be careful not to delete this!
1351     // We need the cast because Array<Klass*> is NOT a supertype of Array<InstanceKlass*>,
1352     // (but it's safe to do here because we won't write into _secondary_supers from this point on).
1353     set_secondary_supers((Array<Klass*>*)(address)interfaces);
1354     return NULL;
1355   } else {
1356     // Copy transitive interfaces to a temporary growable array to be constructed
1357     // into the secondary super list with extra slots.
1358     GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
1359     for (int i = 0; i < interfaces->length(); i++) {
1360       secondaries->push(interfaces->at(i));
1361     }
1362     return secondaries;
1363   }
1364 }
1365 
1366 bool InstanceKlass::implements_interface(Klass* k) const {
1367   if (this == k) return true;
1368   assert(k->is_interface(), "should be an interface class");
1369   for (int i = 0; i < transitive_interfaces()->length(); i++) {
1370     if (transitive_interfaces()->at(i) == k) {
1371       return true;
1372     }
1373   }
1374   return false;
1375 }
1376 
1377 bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
1378   // Verify direct super interface
1379   if (this == k) return true;
1380   assert(k->is_interface(), "should be an interface class");
1381   for (int i = 0; i < local_interfaces()->length(); i++) {
1382     if (local_interfaces()->at(i) == k) {
1383       return true;
1384     }
1385   }
1386   return false;
1387 }
1388 
1389 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
1390   check_array_allocation_length(length, arrayOopDesc::max_array_length(T_OBJECT), CHECK_NULL);
1391   int size = objArrayOopDesc::object_size(length);
1392   Klass* ak = array_klass(n, CHECK_NULL);
1393   objArrayOop o = (objArrayOop)Universe::heap()->array_allocate(ak, size, length,
1394                                                                 /* do_zero */ true, CHECK_NULL);
1395   return o;
1396 }
1397 
1398 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
1399   if (TraceFinalizerRegistration) {
1400     tty->print("Registered ");
1401     i->print_value_on(tty);
1402     tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", p2i(i));
1403   }
1404   instanceHandle h_i(THREAD, i);
1405   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1406   JavaValue result(T_VOID);
1407   JavaCallArguments args(h_i);
1408   methodHandle mh (THREAD, Universe::finalizer_register_method());
1409   JavaCalls::call(&result, mh, &args, CHECK_NULL);
1410   return h_i();
1411 }
1412 
1413 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1414   bool has_finalizer_flag = has_finalizer(); // Query before possible GC
1415   int size = size_helper();  // Query before forming handle.
1416 
1417   instanceOop i;
1418 
1419   i = (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);
1420   if (has_finalizer_flag && !RegisterFinalizersAtInit) {
1421     i = register_finalizer(i, CHECK_NULL);
1422   }
1423   return i;
1424 }
1425 
1426 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1427   return instanceHandle(THREAD, allocate_instance(THREAD));
1428 }
1429 
1430 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1431   if (is_interface() || is_abstract()) {
1432     ResourceMark rm(THREAD);
1433     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1434               : vmSymbols::java_lang_InstantiationException(), external_name());
1435   }
1436   if (this == vmClasses::Class_klass()) {
1437     ResourceMark rm(THREAD);
1438     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1439               : vmSymbols::java_lang_IllegalAccessException(), external_name());
1440   }
1441 }
1442 
1443 Klass* InstanceKlass::array_klass(int n, TRAPS) {
1444   // Need load-acquire for lock-free read
1445   if (array_klasses_acquire() == NULL) {
1446     ResourceMark rm(THREAD);
1447     JavaThread *jt = THREAD;
1448     {
1449       // Atomic creation of array_klasses
1450       MutexLocker ma(THREAD, MultiArray_lock);
1451 
1452       // Check if update has already taken place
1453       if (array_klasses() == NULL) {
1454         ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);

1455         // use 'release' to pair with lock-free load
1456         release_set_array_klasses(k);
1457       }
1458     }
1459   }
1460   // array_klasses() will always be set at this point
1461   ObjArrayKlass* oak = array_klasses();
1462   return oak->array_klass(n, THREAD);
1463 }
1464 
1465 Klass* InstanceKlass::array_klass_or_null(int n) {
1466   // Need load-acquire for lock-free read
1467   ObjArrayKlass* oak = array_klasses_acquire();
1468   if (oak == NULL) {
1469     return NULL;
1470   } else {
1471     return oak->array_klass_or_null(n);
1472   }
1473 }
1474 
1475 Klass* InstanceKlass::array_klass(TRAPS) {
1476   return array_klass(1, THREAD);
1477 }
1478 
1479 Klass* InstanceKlass::array_klass_or_null() {
1480   return array_klass_or_null(1);
1481 }
1482 
1483 static int call_class_initializer_counter = 0;   // for debugging
1484 
1485 Method* InstanceKlass::class_initializer() const {
1486   Method* clinit = find_method(
1487       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1488   if (clinit != NULL && clinit->has_valid_initializer_flags()) {
1489     return clinit;
1490   }
1491   return NULL;
1492 }
1493 
1494 void InstanceKlass::call_class_initializer(TRAPS) {
1495   if (ReplayCompiles &&
1496       (ReplaySuppressInitializers == 1 ||
1497        (ReplaySuppressInitializers >= 2 && class_loader() != NULL))) {
1498     // Hide the existence of the initializer for the purpose of replaying the compile
1499     return;
1500   }
1501 
1502   methodHandle h_method(THREAD, class_initializer());
1503   assert(!is_initialized(), "we cannot initialize twice");
1504   LogTarget(Info, class, init) lt;
1505   if (lt.is_enabled()) {
1506     ResourceMark rm(THREAD);
1507     LogStream ls(lt);
1508     ls.print("%d Initializing ", call_class_initializer_counter++);
1509     name()->print_value_on(&ls);
1510     ls.print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", p2i(this));
1511   }
1512   if (h_method() != NULL) {
1513     JavaCallArguments args; // No arguments
1514     JavaValue result(T_VOID);
1515     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1516   }
1517 }
1518 
1519 
1520 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1521   InterpreterOopMap* entry_for) {
1522   // Lazily create the _oop_map_cache at first request
1523   // Lock-free access requires load_acquire.
1524   OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache);
1525   if (oop_map_cache == NULL) {
1526     MutexLocker x(OopMapCacheAlloc_lock);
1527     // Check if _oop_map_cache was allocated while we were waiting for this lock
1528     if ((oop_map_cache = _oop_map_cache) == NULL) {
1529       oop_map_cache = new OopMapCache();
1530       // Ensure _oop_map_cache is stable, since it is examined without a lock
1531       Atomic::release_store(&_oop_map_cache, oop_map_cache);
1532     }
1533   }
1534   // _oop_map_cache is constant after init; lookup below does its own locking.
1535   oop_map_cache->lookup(method, bci, entry_for);
1536 }
1537 
1538 bool InstanceKlass::contains_field_offset(int offset) {
1539   fieldDescriptor fd;
1540   return find_field_from_offset(offset, false, &fd);
1541 }
1542 
1543 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1544   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1545     Symbol* f_name = fs.name();
1546     Symbol* f_sig  = fs.signature();
1547     if (f_name == name && f_sig == sig) {
1548       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1549       return true;
1550     }
1551   }
1552   return false;
1553 }
1554 
1555 
1556 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1557   const int n = local_interfaces()->length();
1558   for (int i = 0; i < n; i++) {
1559     Klass* intf1 = local_interfaces()->at(i);
1560     assert(intf1->is_interface(), "just checking type");
1561     // search for field in current interface
1562     if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
1563       assert(fd->is_static(), "interface field must be static");
1564       return intf1;
1565     }
1566     // search for field in direct superinterfaces
1567     Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
1568     if (intf2 != NULL) return intf2;
1569   }
1570   // otherwise field lookup fails
1571   return NULL;
1572 }
1573 
1574 
1575 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1576   // search order according to newest JVM spec (5.4.3.2, p.167).
1577   // 1) search for field in current klass
1578   if (find_local_field(name, sig, fd)) {
1579     return const_cast<InstanceKlass*>(this);
1580   }
1581   // 2) search for field recursively in direct superinterfaces
1582   { Klass* intf = find_interface_field(name, sig, fd);
1583     if (intf != NULL) return intf;
1584   }
1585   // 3) apply field lookup recursively if superclass exists
1586   { Klass* supr = super();
1587     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
1588   }
1589   // 4) otherwise field lookup fails
1590   return NULL;
1591 }
1592 
1593 
1594 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1595   // search order according to newest JVM spec (5.4.3.2, p.167).
1596   // 1) search for field in current klass
1597   if (find_local_field(name, sig, fd)) {
1598     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1599   }
1600   // 2) search for field recursively in direct superinterfaces
1601   if (is_static) {
1602     Klass* intf = find_interface_field(name, sig, fd);
1603     if (intf != NULL) return intf;
1604   }
1605   // 3) apply field lookup recursively if superclass exists
1606   { Klass* supr = super();
1607     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
1608   }
1609   // 4) otherwise field lookup fails
1610   return NULL;
1611 }
1612 









1613 
1614 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1615   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1616     if (fs.offset() == offset) {
1617       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1618       if (fd->is_static() == is_static) return true;
1619     }
1620   }
1621   return false;
1622 }
1623 
1624 
1625 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1626   Klass* klass = const_cast<InstanceKlass*>(this);
1627   while (klass != NULL) {
1628     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
1629       return true;
1630     }
1631     klass = klass->super();
1632   }
1633   return false;
1634 }
1635 
1636 
1637 void InstanceKlass::methods_do(void f(Method* method)) {
1638   // Methods aren't stable until they are loaded.  This can be read outside
1639   // a lock through the ClassLoaderData for profiling
1640   if (!is_loaded()) {
1641     return;
1642   }
1643 
1644   int len = methods()->length();
1645   for (int index = 0; index < len; index++) {
1646     Method* m = methods()->at(index);
1647     assert(m->is_method(), "must be method");
1648     f(m);
1649   }
1650 }
1651 
1652 
1653 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
1654   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1655     if (fs.access_flags().is_static()) {
1656       fieldDescriptor& fd = fs.field_descriptor();
1657       cl->do_field(&fd);
1658     }
1659   }
1660 }
1661 
1662 
1663 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
1664   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1665     if (fs.access_flags().is_static()) {
1666       fieldDescriptor& fd = fs.field_descriptor();
1667       f(&fd, mirror, CHECK);
1668     }
1669   }
1670 }
1671 
1672 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
1673   InstanceKlass* super = superklass();
1674   if (super != NULL) {
1675     super->do_nonstatic_fields(cl);
1676   }
1677   fieldDescriptor fd;
1678   int length = java_fields_count();
1679   for (int i = 0; i < length; i += 1) {
1680     fd.reinitialize(this, i);
1681     if (!fd.is_static()) {
1682       cl->do_field(&fd);
1683     }
1684   }
1685 }
1686 
1687 // first in Pair is offset, second is index.
1688 static int compare_fields_by_offset(Pair<int,int>* a, Pair<int,int>* b) {
1689   return a->first - b->first;
1690 }
1691 
1692 void InstanceKlass::print_nonstatic_fields(FieldClosure* cl) {
1693   InstanceKlass* super = superklass();
1694   if (super != NULL) {
1695     super->print_nonstatic_fields(cl);
1696   }
1697   ResourceMark rm;
1698   fieldDescriptor fd;
1699   // In DebugInfo nonstatic fields are sorted by offset.
1700   GrowableArray<Pair<int,int> > fields_sorted;
1701   int i = 0;
1702   for (AllFieldStream fs(this); !fs.done(); fs.next()) {
1703     if (!fs.access_flags().is_static()) {
1704       fd = fs.field_descriptor();
1705       Pair<int,int> f(fs.offset(), fs.index());
1706       fields_sorted.push(f);
1707       i++;
1708     }
1709   }
1710   if (i > 0) {
1711     int length = i;
1712     assert(length == fields_sorted.length(), "duh");
1713     // _sort_Fn is defined in growableArray.hpp.
1714     fields_sorted.sort(compare_fields_by_offset);
1715     for (int i = 0; i < length; i++) {
1716       fd.reinitialize(this, fields_sorted.at(i).second);
1717       assert(!fd.is_static() && fd.offset() == fields_sorted.at(i).first, "only nonstatic fields");
1718       cl->do_field(&fd);
1719     }
1720   }
1721 }
1722 
1723 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
1724   if (array_klasses() != NULL)
1725     array_klasses()->array_klasses_do(f, THREAD);
1726 }
1727 
1728 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
1729   if (array_klasses() != NULL)
1730     array_klasses()->array_klasses_do(f);
1731 }
1732 
1733 #ifdef ASSERT
1734 static int linear_search(const Array<Method*>* methods,
1735                          const Symbol* name,
1736                          const Symbol* signature) {
1737   const int len = methods->length();
1738   for (int index = 0; index < len; index++) {
1739     const Method* const m = methods->at(index);
1740     assert(m->is_method(), "must be method");
1741     if (m->signature() == signature && m->name() == name) {
1742        return index;
1743     }
1744   }
1745   return -1;
1746 }
1747 #endif
1748 
1749 bool InstanceKlass::_disable_method_binary_search = false;
1750 
1751 NOINLINE int linear_search(const Array<Method*>* methods, const Symbol* name) {
1752   int len = methods->length();
1753   int l = 0;
1754   int h = len - 1;
1755   while (l <= h) {
1756     Method* m = methods->at(l);
1757     if (m->name() == name) {
1758       return l;
1759     }
1760     l++;
1761   }
1762   return -1;
1763 }
1764 
1765 inline int InstanceKlass::quick_search(const Array<Method*>* methods, const Symbol* name) {
1766   if (_disable_method_binary_search) {
1767     assert(DynamicDumpSharedSpaces, "must be");
1768     // At the final stage of dynamic dumping, the methods array may not be sorted
1769     // by ascending addresses of their names, so we can't use binary search anymore.
1770     // However, methods with the same name are still laid out consecutively inside the
1771     // methods array, so let's look for the first one that matches.
1772     return linear_search(methods, name);
1773   }
1774 
1775   int len = methods->length();
1776   int l = 0;
1777   int h = len - 1;
1778 
1779   // methods are sorted by ascending addresses of their names, so do binary search
1780   while (l <= h) {
1781     int mid = (l + h) >> 1;
1782     Method* m = methods->at(mid);
1783     assert(m->is_method(), "must be method");
1784     int res = m->name()->fast_compare(name);
1785     if (res == 0) {
1786       return mid;
1787     } else if (res < 0) {
1788       l = mid + 1;
1789     } else {
1790       h = mid - 1;
1791     }
1792   }
1793   return -1;
1794 }
1795 
1796 // find_method looks up the name/signature in the local methods array
1797 Method* InstanceKlass::find_method(const Symbol* name,
1798                                    const Symbol* signature) const {
1799   return find_method_impl(name, signature,
1800                           OverpassLookupMode::find,
1801                           StaticLookupMode::find,
1802                           PrivateLookupMode::find);
1803 }
1804 
1805 Method* InstanceKlass::find_method_impl(const Symbol* name,
1806                                         const Symbol* signature,
1807                                         OverpassLookupMode overpass_mode,
1808                                         StaticLookupMode static_mode,
1809                                         PrivateLookupMode private_mode) const {
1810   return InstanceKlass::find_method_impl(methods(),
1811                                          name,
1812                                          signature,
1813                                          overpass_mode,
1814                                          static_mode,
1815                                          private_mode);
1816 }
1817 
1818 // find_instance_method looks up the name/signature in the local methods array
1819 // and skips over static methods
1820 Method* InstanceKlass::find_instance_method(const Array<Method*>* methods,
1821                                             const Symbol* name,
1822                                             const Symbol* signature,
1823                                             PrivateLookupMode private_mode) {
1824   Method* const meth = InstanceKlass::find_method_impl(methods,
1825                                                  name,
1826                                                  signature,
1827                                                  OverpassLookupMode::find,
1828                                                  StaticLookupMode::skip,
1829                                                  private_mode);
1830   assert(((meth == NULL) || !meth->is_static()),
1831     "find_instance_method should have skipped statics");
1832   return meth;
1833 }
1834 
1835 // find_instance_method looks up the name/signature in the local methods array
1836 // and skips over static methods
1837 Method* InstanceKlass::find_instance_method(const Symbol* name,
1838                                             const Symbol* signature,
1839                                             PrivateLookupMode private_mode) const {
1840   return InstanceKlass::find_instance_method(methods(), name, signature, private_mode);
1841 }
1842 
1843 // Find looks up the name/signature in the local methods array
1844 // and filters on the overpass, static and private flags
1845 // This returns the first one found
1846 // note that the local methods array can have up to one overpass, one static
1847 // and one instance (private or not) with the same name/signature
1848 Method* InstanceKlass::find_local_method(const Symbol* name,
1849                                          const Symbol* signature,
1850                                          OverpassLookupMode overpass_mode,
1851                                          StaticLookupMode static_mode,
1852                                          PrivateLookupMode private_mode) const {
1853   return InstanceKlass::find_method_impl(methods(),
1854                                          name,
1855                                          signature,
1856                                          overpass_mode,
1857                                          static_mode,
1858                                          private_mode);
1859 }
1860 
1861 // Find looks up the name/signature in the local methods array
1862 // and filters on the overpass, static and private flags
1863 // This returns the first one found
1864 // note that the local methods array can have up to one overpass, one static
1865 // and one instance (private or not) with the same name/signature
1866 Method* InstanceKlass::find_local_method(const Array<Method*>* methods,
1867                                          const Symbol* name,
1868                                          const Symbol* signature,
1869                                          OverpassLookupMode overpass_mode,
1870                                          StaticLookupMode static_mode,
1871                                          PrivateLookupMode private_mode) {
1872   return InstanceKlass::find_method_impl(methods,
1873                                          name,
1874                                          signature,
1875                                          overpass_mode,
1876                                          static_mode,
1877                                          private_mode);
1878 }
1879 
1880 Method* InstanceKlass::find_method(const Array<Method*>* methods,
1881                                    const Symbol* name,
1882                                    const Symbol* signature) {
1883   return InstanceKlass::find_method_impl(methods,
1884                                          name,
1885                                          signature,
1886                                          OverpassLookupMode::find,
1887                                          StaticLookupMode::find,
1888                                          PrivateLookupMode::find);
1889 }
1890 
1891 Method* InstanceKlass::find_method_impl(const Array<Method*>* methods,
1892                                         const Symbol* name,
1893                                         const Symbol* signature,
1894                                         OverpassLookupMode overpass_mode,
1895                                         StaticLookupMode static_mode,
1896                                         PrivateLookupMode private_mode) {
1897   int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode);
1898   return hit >= 0 ? methods->at(hit): NULL;
1899 }
1900 
1901 // true if method matches signature and conforms to skipping_X conditions.
1902 static bool method_matches(const Method* m,
1903                            const Symbol* signature,
1904                            bool skipping_overpass,
1905                            bool skipping_static,
1906                            bool skipping_private) {
1907   return ((m->signature() == signature) &&
1908     (!skipping_overpass || !m->is_overpass()) &&
1909     (!skipping_static || !m->is_static()) &&
1910     (!skipping_private || !m->is_private()));
1911 }
1912 
1913 // Used directly for default_methods to find the index into the
1914 // default_vtable_indices, and indirectly by find_method
1915 // find_method_index looks in the local methods array to return the index
1916 // of the matching name/signature. If, overpass methods are being ignored,
1917 // the search continues to find a potential non-overpass match.  This capability
1918 // is important during method resolution to prefer a static method, for example,
1919 // over an overpass method.
1920 // There is the possibility in any _method's array to have the same name/signature
1921 // for a static method, an overpass method and a local instance method
1922 // To correctly catch a given method, the search criteria may need
1923 // to explicitly skip the other two. For local instance methods, it
1924 // is often necessary to skip private methods
1925 int InstanceKlass::find_method_index(const Array<Method*>* methods,
1926                                      const Symbol* name,
1927                                      const Symbol* signature,
1928                                      OverpassLookupMode overpass_mode,
1929                                      StaticLookupMode static_mode,
1930                                      PrivateLookupMode private_mode) {
1931   const bool skipping_overpass = (overpass_mode == OverpassLookupMode::skip);
1932   const bool skipping_static = (static_mode == StaticLookupMode::skip);
1933   const bool skipping_private = (private_mode == PrivateLookupMode::skip);
1934   const int hit = quick_search(methods, name);
1935   if (hit != -1) {
1936     const Method* const m = methods->at(hit);
1937 
1938     // Do linear search to find matching signature.  First, quick check
1939     // for common case, ignoring overpasses if requested.
1940     if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1941       return hit;
1942     }
1943 
1944     // search downwards through overloaded methods
1945     int i;
1946     for (i = hit - 1; i >= 0; --i) {
1947         const Method* const m = methods->at(i);
1948         assert(m->is_method(), "must be method");
1949         if (m->name() != name) {
1950           break;
1951         }
1952         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1953           return i;
1954         }
1955     }
1956     // search upwards
1957     for (i = hit + 1; i < methods->length(); ++i) {
1958         const Method* const m = methods->at(i);
1959         assert(m->is_method(), "must be method");
1960         if (m->name() != name) {
1961           break;
1962         }
1963         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1964           return i;
1965         }
1966     }
1967     // not found
1968 #ifdef ASSERT
1969     const int index = (skipping_overpass || skipping_static || skipping_private) ? -1 :
1970       linear_search(methods, name, signature);
1971     assert(-1 == index, "binary search should have found entry %d", index);
1972 #endif
1973   }
1974   return -1;
1975 }
1976 
1977 int InstanceKlass::find_method_by_name(const Symbol* name, int* end) const {
1978   return find_method_by_name(methods(), name, end);
1979 }
1980 
1981 int InstanceKlass::find_method_by_name(const Array<Method*>* methods,
1982                                        const Symbol* name,
1983                                        int* end_ptr) {
1984   assert(end_ptr != NULL, "just checking");
1985   int start = quick_search(methods, name);
1986   int end = start + 1;
1987   if (start != -1) {
1988     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
1989     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
1990     *end_ptr = end;
1991     return start;
1992   }
1993   return -1;
1994 }
1995 
1996 // uncached_lookup_method searches both the local class methods array and all
1997 // superclasses methods arrays, skipping any overpass methods in superclasses,
1998 // and possibly skipping private methods.
1999 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2000                                               const Symbol* signature,
2001                                               OverpassLookupMode overpass_mode,
2002                                               PrivateLookupMode private_mode) const {
2003   OverpassLookupMode overpass_local_mode = overpass_mode;
2004   const Klass* klass = this;
2005   while (klass != NULL) {
2006     Method* const method = InstanceKlass::cast(klass)->find_method_impl(name,
2007                                                                         signature,
2008                                                                         overpass_local_mode,
2009                                                                         StaticLookupMode::find,
2010                                                                         private_mode);
2011     if (method != NULL) {
2012       return method;
2013     }



2014     klass = klass->super();
2015     overpass_local_mode = OverpassLookupMode::skip;   // Always ignore overpass methods in superclasses
2016   }
2017   return NULL;
2018 }
2019 
2020 #ifdef ASSERT
2021 // search through class hierarchy and return true if this class or
2022 // one of the superclasses was redefined
2023 bool InstanceKlass::has_redefined_this_or_super() const {
2024   const Klass* klass = this;
2025   while (klass != NULL) {
2026     if (InstanceKlass::cast(klass)->has_been_redefined()) {
2027       return true;
2028     }
2029     klass = klass->super();
2030   }
2031   return false;
2032 }
2033 #endif
2034 
2035 // lookup a method in the default methods list then in all transitive interfaces
2036 // Do NOT return private or static methods
2037 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
2038                                                          Symbol* signature) const {
2039   Method* m = NULL;
2040   if (default_methods() != NULL) {
2041     m = find_method(default_methods(), name, signature);
2042   }
2043   // Look up interfaces
2044   if (m == NULL) {
2045     m = lookup_method_in_all_interfaces(name, signature, DefaultsLookupMode::find);
2046   }
2047   return m;
2048 }
2049 
2050 // lookup a method in all the interfaces that this class implements
2051 // Do NOT return private or static methods, new in JDK8 which are not externally visible
2052 // They should only be found in the initial InterfaceMethodRef
2053 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
2054                                                        Symbol* signature,
2055                                                        DefaultsLookupMode defaults_mode) const {
2056   Array<InstanceKlass*>* all_ifs = transitive_interfaces();
2057   int num_ifs = all_ifs->length();
2058   InstanceKlass *ik = NULL;
2059   for (int i = 0; i < num_ifs; i++) {
2060     ik = all_ifs->at(i);
2061     Method* m = ik->lookup_method(name, signature);
2062     if (m != NULL && m->is_public() && !m->is_static() &&
2063         ((defaults_mode != DefaultsLookupMode::skip) || !m->is_default_method())) {
2064       return m;
2065     }
2066   }
2067   return NULL;
2068 }
2069 
2070 /* jni_id_for_impl for jfieldIds only */
2071 JNIid* InstanceKlass::jni_id_for_impl(int offset) {
2072   MutexLocker ml(JfieldIdCreation_lock);
2073   // Retry lookup after we got the lock
2074   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
2075   if (probe == NULL) {
2076     // Slow case, allocate new static field identifier
2077     probe = new JNIid(this, offset, jni_ids());
2078     set_jni_ids(probe);
2079   }
2080   return probe;
2081 }
2082 
2083 
2084 /* jni_id_for for jfieldIds only */
2085 JNIid* InstanceKlass::jni_id_for(int offset) {
2086   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
2087   if (probe == NULL) {
2088     probe = jni_id_for_impl(offset);
2089   }
2090   return probe;
2091 }
2092 
2093 u2 InstanceKlass::enclosing_method_data(int offset) const {
2094   const Array<jushort>* const inner_class_list = inner_classes();
2095   if (inner_class_list == NULL) {
2096     return 0;
2097   }
2098   const int length = inner_class_list->length();
2099   if (length % inner_class_next_offset == 0) {
2100     return 0;
2101   }
2102   const int index = length - enclosing_method_attribute_size;
2103   assert(offset < enclosing_method_attribute_size, "invalid offset");
2104   return inner_class_list->at(index + offset);
2105 }
2106 
2107 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
2108                                                  u2 method_index) {
2109   Array<jushort>* inner_class_list = inner_classes();
2110   assert (inner_class_list != NULL, "_inner_classes list is not set up");
2111   int length = inner_class_list->length();
2112   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
2113     int index = length - enclosing_method_attribute_size;
2114     inner_class_list->at_put(
2115       index + enclosing_method_class_index_offset, class_index);
2116     inner_class_list->at_put(
2117       index + enclosing_method_method_index_offset, method_index);
2118   }
2119 }
2120 
2121 // Lookup or create a jmethodID.
2122 // This code is called by the VMThread and JavaThreads so the
2123 // locking has to be done very carefully to avoid deadlocks
2124 // and/or other cache consistency problems.
2125 //
2126 jmethodID InstanceKlass::get_jmethod_id(const methodHandle& method_h) {
2127   size_t idnum = (size_t)method_h->method_idnum();
2128   jmethodID* jmeths = methods_jmethod_ids_acquire();
2129   size_t length = 0;
2130   jmethodID id = NULL;
2131 
2132   // We use a double-check locking idiom here because this cache is
2133   // performance sensitive. In the normal system, this cache only
2134   // transitions from NULL to non-NULL which is safe because we use
2135   // release_set_methods_jmethod_ids() to advertise the new cache.
2136   // A partially constructed cache should never be seen by a racing
2137   // thread. We also use release_store() to save a new jmethodID
2138   // in the cache so a partially constructed jmethodID should never be
2139   // seen either. Cache reads of existing jmethodIDs proceed without a
2140   // lock, but cache writes of a new jmethodID requires uniqueness and
2141   // creation of the cache itself requires no leaks so a lock is
2142   // generally acquired in those two cases.
2143   //
2144   // If the RedefineClasses() API has been used, then this cache can
2145   // grow and we'll have transitions from non-NULL to bigger non-NULL.
2146   // Cache creation requires no leaks and we require safety between all
2147   // cache accesses and freeing of the old cache so a lock is generally
2148   // acquired when the RedefineClasses() API has been used.
2149 
2150   if (jmeths != NULL) {
2151     // the cache already exists
2152     if (!idnum_can_increment()) {
2153       // the cache can't grow so we can just get the current values
2154       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
2155     } else {
2156       // cache can grow so we have to be more careful
2157       if (Threads::number_of_threads() == 0 ||
2158           SafepointSynchronize::is_at_safepoint()) {
2159         // we're single threaded or at a safepoint - no locking needed
2160         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
2161       } else {
2162         MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag);
2163         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
2164       }
2165     }
2166   }
2167   // implied else:
2168   // we need to allocate a cache so default length and id values are good
2169 
2170   if (jmeths == NULL ||   // no cache yet
2171       length <= idnum ||  // cache is too short
2172       id == NULL) {       // cache doesn't contain entry
2173 
2174     // This function can be called by the VMThread so we have to do all
2175     // things that might block on a safepoint before grabbing the lock.
2176     // Otherwise, we can deadlock with the VMThread or have a cache
2177     // consistency issue. These vars keep track of what we might have
2178     // to free after the lock is dropped.
2179     jmethodID  to_dealloc_id     = NULL;
2180     jmethodID* to_dealloc_jmeths = NULL;
2181 
2182     // may not allocate new_jmeths or use it if we allocate it
2183     jmethodID* new_jmeths = NULL;
2184     if (length <= idnum) {
2185       // allocate a new cache that might be used
2186       size_t size = MAX2(idnum+1, (size_t)idnum_allocated_count());
2187       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
2188       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
2189       // cache size is stored in element[0], other elements offset by one
2190       new_jmeths[0] = (jmethodID)size;
2191     }
2192 
2193     // allocate a new jmethodID that might be used
2194     jmethodID new_id = NULL;
2195     if (method_h->is_old() && !method_h->is_obsolete()) {
2196       // The method passed in is old (but not obsolete), we need to use the current version
2197       Method* current_method = method_with_idnum((int)idnum);
2198       assert(current_method != NULL, "old and but not obsolete, so should exist");
2199       new_id = Method::make_jmethod_id(class_loader_data(), current_method);
2200     } else {
2201       // It is the current version of the method or an obsolete method,
2202       // use the version passed in
2203       new_id = Method::make_jmethod_id(class_loader_data(), method_h());
2204     }
2205 
2206     if (Threads::number_of_threads() == 0 ||
2207         SafepointSynchronize::is_at_safepoint()) {
2208       // we're single threaded or at a safepoint - no locking needed
2209       id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,
2210                                           &to_dealloc_id, &to_dealloc_jmeths);
2211     } else {
2212       MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag);
2213       id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,
2214                                           &to_dealloc_id, &to_dealloc_jmeths);
2215     }
2216 
2217     // The lock has been dropped so we can free resources.
2218     // Free up either the old cache or the new cache if we allocated one.
2219     if (to_dealloc_jmeths != NULL) {
2220       FreeHeap(to_dealloc_jmeths);
2221     }
2222     // free up the new ID since it wasn't needed
2223     if (to_dealloc_id != NULL) {
2224       Method::destroy_jmethod_id(class_loader_data(), to_dealloc_id);
2225     }
2226   }
2227   return id;
2228 }
2229 
2230 // Figure out how many jmethodIDs haven't been allocated, and make
2231 // sure space for them is pre-allocated.  This makes getting all
2232 // method ids much, much faster with classes with more than 8
2233 // methods, and has a *substantial* effect on performance with jvmti
2234 // code that loads all jmethodIDs for all classes.
2235 void InstanceKlass::ensure_space_for_methodids(int start_offset) {
2236   int new_jmeths = 0;
2237   int length = methods()->length();
2238   for (int index = start_offset; index < length; index++) {
2239     Method* m = methods()->at(index);
2240     jmethodID id = m->find_jmethod_id_or_null();
2241     if (id == NULL) {
2242       new_jmeths++;
2243     }
2244   }
2245   if (new_jmeths != 0) {
2246     Method::ensure_jmethod_ids(class_loader_data(), new_jmeths);
2247   }
2248 }
2249 
2250 // Common code to fetch the jmethodID from the cache or update the
2251 // cache with the new jmethodID. This function should never do anything
2252 // that causes the caller to go to a safepoint or we can deadlock with
2253 // the VMThread or have cache consistency issues.
2254 //
2255 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
2256             size_t idnum, jmethodID new_id,
2257             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
2258             jmethodID** to_dealloc_jmeths_p) {
2259   assert(new_id != NULL, "sanity check");
2260   assert(to_dealloc_id_p != NULL, "sanity check");
2261   assert(to_dealloc_jmeths_p != NULL, "sanity check");
2262   assert(Threads::number_of_threads() == 0 ||
2263          SafepointSynchronize::is_at_safepoint() ||
2264          JmethodIdCreation_lock->owned_by_self(), "sanity check");
2265 
2266   // reacquire the cache - we are locked, single threaded or at a safepoint
2267   jmethodID* jmeths = methods_jmethod_ids_acquire();
2268   jmethodID  id     = NULL;
2269   size_t     length = 0;
2270 
2271   if (jmeths == NULL ||                         // no cache yet
2272       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
2273     if (jmeths != NULL) {
2274       // copy any existing entries from the old cache
2275       for (size_t index = 0; index < length; index++) {
2276         new_jmeths[index+1] = jmeths[index+1];
2277       }
2278       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
2279     }
2280     release_set_methods_jmethod_ids(jmeths = new_jmeths);
2281   } else {
2282     // fetch jmethodID (if any) from the existing cache
2283     id = jmeths[idnum+1];
2284     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
2285   }
2286   if (id == NULL) {
2287     // No matching jmethodID in the existing cache or we have a new
2288     // cache or we just grew the cache. This cache write is done here
2289     // by the first thread to win the foot race because a jmethodID
2290     // needs to be unique once it is generally available.
2291     id = new_id;
2292 
2293     // The jmethodID cache can be read while unlocked so we have to
2294     // make sure the new jmethodID is complete before installing it
2295     // in the cache.
2296     Atomic::release_store(&jmeths[idnum+1], id);
2297   } else {
2298     *to_dealloc_id_p = new_id; // save new id for later delete
2299   }
2300   return id;
2301 }
2302 
2303 
2304 // Common code to get the jmethodID cache length and the jmethodID
2305 // value at index idnum if there is one.
2306 //
2307 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
2308        size_t idnum, size_t *length_p, jmethodID* id_p) {
2309   assert(cache != NULL, "sanity check");
2310   assert(length_p != NULL, "sanity check");
2311   assert(id_p != NULL, "sanity check");
2312 
2313   // cache size is stored in element[0], other elements offset by one
2314   *length_p = (size_t)cache[0];
2315   if (*length_p <= idnum) {  // cache is too short
2316     *id_p = NULL;
2317   } else {
2318     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
2319   }
2320 }
2321 
2322 
2323 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
2324 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
2325   size_t idnum = (size_t)method->method_idnum();
2326   jmethodID* jmeths = methods_jmethod_ids_acquire();
2327   size_t length;                                // length assigned as debugging crumb
2328   jmethodID id = NULL;
2329   if (jmeths != NULL &&                         // If there is a cache
2330       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
2331     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
2332   }
2333   return id;
2334 }
2335 
2336 inline DependencyContext InstanceKlass::dependencies() {
2337   DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);
2338   return dep_context;
2339 }
2340 
2341 int InstanceKlass::mark_dependent_nmethods(KlassDepChange& changes) {
2342   return dependencies().mark_dependent_nmethods(changes);
2343 }
2344 
2345 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2346   dependencies().add_dependent_nmethod(nm);
2347 }
2348 
2349 void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
2350   dependencies().remove_dependent_nmethod(nm);
2351 }
2352 
2353 void InstanceKlass::clean_dependency_context() {
2354   dependencies().clean_unloading_dependents();
2355 }
2356 
2357 #ifndef PRODUCT
2358 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2359   dependencies().print_dependent_nmethods(verbose);
2360 }
2361 
2362 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2363   return dependencies().is_dependent_nmethod(nm);
2364 }
2365 #endif //PRODUCT
2366 
2367 void InstanceKlass::clean_weak_instanceklass_links() {
2368   clean_implementors_list();
2369   clean_method_data();
2370 }
2371 
2372 void InstanceKlass::clean_implementors_list() {
2373   assert(is_loader_alive(), "this klass should be live");
2374   if (is_interface()) {
2375     assert (ClassUnloading, "only called for ClassUnloading");
2376     for (;;) {
2377       // Use load_acquire due to competing with inserts
2378       InstanceKlass* impl = Atomic::load_acquire(adr_implementor());
2379       if (impl != NULL && !impl->is_loader_alive()) {
2380         // NULL this field, might be an unloaded instance klass or NULL
2381         InstanceKlass* volatile* iklass = adr_implementor();
2382         if (Atomic::cmpxchg(iklass, impl, (InstanceKlass*)NULL) == impl) {
2383           // Successfully unlinking implementor.
2384           if (log_is_enabled(Trace, class, unload)) {
2385             ResourceMark rm;
2386             log_trace(class, unload)("unlinking class (implementor): %s", impl->external_name());
2387           }
2388           return;
2389         }
2390       } else {
2391         return;
2392       }
2393     }
2394   }
2395 }
2396 
2397 void InstanceKlass::clean_method_data() {
2398   for (int m = 0; m < methods()->length(); m++) {
2399     MethodData* mdo = methods()->at(m)->method_data();
2400     if (mdo != NULL) {
2401       MutexLocker ml(SafepointSynchronize::is_at_safepoint() ? NULL : mdo->extra_data_lock());
2402       mdo->clean_method_data(/*always_clean*/false);
2403     }
2404   }
2405 }
2406 
2407 void InstanceKlass::metaspace_pointers_do(MetaspaceClosure* it) {
2408   Klass::metaspace_pointers_do(it);
2409 
2410   if (log_is_enabled(Trace, cds)) {
2411     ResourceMark rm;
2412     log_trace(cds)("Iter(InstanceKlass): %p (%s)", this, external_name());
2413   }
2414 
2415   it->push(&_annotations);
2416   it->push((Klass**)&_array_klasses);
2417   if (!is_rewritten()) {
2418     it->push(&_constants, MetaspaceClosure::_writable);
2419   } else {
2420     it->push(&_constants);
2421   }
2422   it->push(&_inner_classes);
2423 #if INCLUDE_JVMTI
2424   it->push(&_previous_versions);
2425 #endif
2426   it->push(&_methods);
2427   it->push(&_default_methods);
2428   it->push(&_local_interfaces);
2429   it->push(&_transitive_interfaces);
2430   it->push(&_method_ordering);
2431   if (!is_rewritten()) {
2432     it->push(&_default_vtable_indices, MetaspaceClosure::_writable);
2433   } else {
2434     it->push(&_default_vtable_indices);
2435   }
2436   it->push(&_fields);
2437 
2438   if (itable_length() > 0) {
2439     itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2440     int method_table_offset_in_words = ioe->offset()/wordSize;
2441     int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2442                          / itableOffsetEntry::size();
2443 
2444     for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2445       if (ioe->interface_klass() != NULL) {
2446         it->push(ioe->interface_klass_addr());
2447         itableMethodEntry* ime = ioe->first_method_entry(this);
2448         int n = klassItable::method_count_for_interface(ioe->interface_klass());
2449         for (int index = 0; index < n; index ++) {
2450           it->push(ime[index].method_addr());
2451         }
2452       }
2453     }
2454   }
2455 
2456   it->push(&_nest_members);
2457   it->push(&_permitted_subclasses);
2458   it->push(&_record_components);






2459 }
2460 
2461 void InstanceKlass::remove_unshareable_info() {
2462 
2463   if (is_linked()) {
2464     assert(can_be_verified_at_dumptime(), "must be");
2465     // Remember this so we can avoid walking the hierarchy at runtime.
2466     set_verified_at_dump_time();
2467   }
2468 
2469   Klass::remove_unshareable_info();
2470 
2471   if (SystemDictionaryShared::has_class_failed_verification(this)) {
2472     // Classes are attempted to link during dumping and may fail,
2473     // but these classes are still in the dictionary and class list in CLD.
2474     // If the class has failed verification, there is nothing else to remove.
2475     return;
2476   }
2477 
2478   // Reset to the 'allocated' state to prevent any premature accessing to
2479   // a shared class at runtime while the class is still being loaded and
2480   // restored. A class' init_state is set to 'loaded' at runtime when it's
2481   // being added to class hierarchy (see SystemDictionary:::add_to_hierarchy()).
2482   _init_state = allocated;
2483 
2484   { // Otherwise this needs to take out the Compile_lock.
2485     assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2486     init_implementor();
2487   }
2488 
2489   constants()->remove_unshareable_info();
2490 
2491   for (int i = 0; i < methods()->length(); i++) {
2492     Method* m = methods()->at(i);
2493     m->remove_unshareable_info();
2494   }
2495 
2496   // do array classes also.
2497   if (array_klasses() != NULL) {
2498     array_klasses()->remove_unshareable_info();
2499   }
2500 








2501   // These are not allocated from metaspace. They are safe to set to NULL.
2502   _source_debug_extension = NULL;
2503   _dep_context = NULL;
2504   _osr_nmethods_head = NULL;
2505 #if INCLUDE_JVMTI
2506   _breakpoints = NULL;
2507   _previous_versions = NULL;
2508   _cached_class_file = NULL;
2509   _jvmti_cached_class_field_map = NULL;
2510 #endif
2511 
2512   _init_thread = NULL;
2513   _methods_jmethod_ids = NULL;
2514   _jni_ids = NULL;
2515   _oop_map_cache = NULL;
2516   // clear _nest_host to ensure re-load at runtime
2517   _nest_host = NULL;
2518   init_shared_package_entry();
2519   _dep_context_last_cleaned = 0;
2520 }
2521 
2522 void InstanceKlass::remove_java_mirror() {
2523   Klass::remove_java_mirror();
2524 
2525   // do array classes also.
2526   if (array_klasses() != NULL) {
2527     array_klasses()->remove_java_mirror();
2528   }
2529 }
2530 
2531 void InstanceKlass::init_shared_package_entry() {
2532 #if !INCLUDE_CDS_JAVA_HEAP
2533   _package_entry = NULL;
2534 #else
2535   if (!MetaspaceShared::use_full_module_graph()) {
2536     _package_entry = NULL;
2537   } else if (DynamicDumpSharedSpaces) {
2538     if (!MetaspaceShared::is_in_shared_metaspace(_package_entry)) {
2539       _package_entry = NULL;
2540     }
2541   } else {
2542     if (is_shared_unregistered_class()) {
2543       _package_entry = NULL;
2544     } else {
2545       _package_entry = PackageEntry::get_archived_entry(_package_entry);
2546     }
2547   }
2548   ArchivePtrMarker::mark_pointer((address**)&_package_entry);
2549 #endif
2550 }
2551 
2552 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
2553                                              PackageEntry* pkg_entry, TRAPS) {
2554   // SystemDictionary::add_to_hierarchy() sets the init_state to loaded
2555   // before the InstanceKlass is added to the SystemDictionary. Make
2556   // sure the current state is <loaded.
2557   assert(!is_loaded(), "invalid init state");
2558   assert(!shared_loading_failed(), "Must not try to load failed class again");
2559   set_package(loader_data, pkg_entry, CHECK);
2560   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2561 




2562   Array<Method*>* methods = this->methods();
2563   int num_methods = methods->length();
2564   for (int index = 0; index < num_methods; ++index) {
2565     methods->at(index)->restore_unshareable_info(CHECK);
2566   }
2567 #if INCLUDE_JVMTI
2568   if (JvmtiExport::has_redefined_a_class()) {
2569     // Reinitialize vtable because RedefineClasses may have changed some
2570     // entries in this vtable for super classes so the CDS vtable might
2571     // point to old or obsolete entries.  RedefineClasses doesn't fix up
2572     // vtables in the shared system dictionary, only the main one.
2573     // It also redefines the itable too so fix that too.
2574     // First fix any default methods that point to a super class that may
2575     // have been redefined.
2576     bool trace_name_printed = false;
2577     adjust_default_methods(&trace_name_printed);
2578     vtable().initialize_vtable();
2579     itable().initialize_itable();
2580   }
2581 #endif
2582 
2583   // restore constant pool resolved references
2584   constants()->restore_unshareable_info(CHECK);
2585 
2586   if (array_klasses() != NULL) {
2587     // Array classes have null protection domain.
2588     // --> see ArrayKlass::complete_create_array_klass()
2589     array_klasses()->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);
2590   }
2591 
2592   // Initialize @ValueBased class annotation
2593   if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation()) {
2594     set_is_value_based();
2595   }
2596 }
2597 
2598 // Check if a class or any of its supertypes has a version older than 50.
2599 // CDS will not perform verification of old classes during dump time because
2600 // without changing the old verifier, the verification constraint cannot be
2601 // retrieved during dump time.
2602 // Verification of archived old classes will be performed during run time.
2603 bool InstanceKlass::can_be_verified_at_dumptime() const {
2604   if (major_version() < 50 /*JAVA_6_VERSION*/) {
2605     return false;
2606   }
2607   if (java_super() != NULL && !java_super()->can_be_verified_at_dumptime()) {
2608     return false;
2609   }
2610   Array<InstanceKlass*>* interfaces = local_interfaces();
2611   int len = interfaces->length();
2612   for (int i = 0; i < len; i++) {
2613     if (!interfaces->at(i)->can_be_verified_at_dumptime()) {
2614       return false;
2615     }
2616   }
2617   return true;
2618 }
2619 
2620 void InstanceKlass::set_shared_class_loader_type(s2 loader_type) {
2621   switch (loader_type) {
2622   case ClassLoader::BOOT_LOADER:
2623     _misc_flags |= _misc_is_shared_boot_class;
2624     break;
2625   case ClassLoader::PLATFORM_LOADER:
2626     _misc_flags |= _misc_is_shared_platform_class;
2627     break;
2628   case ClassLoader::APP_LOADER:
2629     _misc_flags |= _misc_is_shared_app_class;
2630     break;
2631   default:
2632     ShouldNotReachHere();
2633     break;
2634   }
2635 }
2636 
2637 void InstanceKlass::assign_class_loader_type() {
2638   ClassLoaderData *cld = class_loader_data();
2639   if (cld->is_boot_class_loader_data()) {
2640     set_shared_class_loader_type(ClassLoader::BOOT_LOADER);
2641   }
2642   else if (cld->is_platform_class_loader_data()) {
2643     set_shared_class_loader_type(ClassLoader::PLATFORM_LOADER);
2644   }
2645   else if (cld->is_system_class_loader_data()) {
2646     set_shared_class_loader_type(ClassLoader::APP_LOADER);
2647   }
2648 }
2649 
2650 #if INCLUDE_JVMTI
2651 static void clear_all_breakpoints(Method* m) {
2652   m->clear_all_breakpoints();
2653 }
2654 #endif
2655 
2656 void InstanceKlass::unload_class(InstanceKlass* ik) {
2657   // Release dependencies.
2658   ik->dependencies().remove_all_dependents();
2659 
2660   // notify the debugger
2661   if (JvmtiExport::should_post_class_unload()) {
2662     JvmtiExport::post_class_unload(ik);
2663   }
2664 
2665   // notify ClassLoadingService of class unload
2666   ClassLoadingService::notify_class_unloaded(ik);
2667 
2668   SystemDictionaryShared::handle_class_unloading(ik);
2669 
2670   if (log_is_enabled(Info, class, unload)) {
2671     ResourceMark rm;
2672     log_info(class, unload)("unloading class %s " INTPTR_FORMAT, ik->external_name(), p2i(ik));
2673   }
2674 
2675   Events::log_class_unloading(Thread::current(), ik);
2676 
2677 #if INCLUDE_JFR
2678   assert(ik != NULL, "invariant");
2679   EventClassUnload event;
2680   event.set_unloadedClass(ik);
2681   event.set_definingClassLoader(ik->class_loader_data());
2682   event.commit();
2683 #endif
2684 }
2685 
2686 static void method_release_C_heap_structures(Method* m) {
2687   m->release_C_heap_structures();
2688 }
2689 
2690 void InstanceKlass::release_C_heap_structures() {
2691 
2692   // Clean up C heap
2693   release_C_heap_structures_internal();
2694   constants()->release_C_heap_structures();
2695 
2696   // Deallocate and call destructors for MDO mutexes
2697   methods_do(method_release_C_heap_structures);
2698 }
2699 
2700 void InstanceKlass::release_C_heap_structures_internal() {
2701   Klass::release_C_heap_structures();
2702 
2703   // Can't release the constant pool here because the constant pool can be
2704   // deallocated separately from the InstanceKlass for default methods and
2705   // redefine classes.
2706 
2707   // Deallocate oop map cache
2708   if (_oop_map_cache != NULL) {
2709     delete _oop_map_cache;
2710     _oop_map_cache = NULL;
2711   }
2712 
2713   // Deallocate JNI identifiers for jfieldIDs
2714   JNIid::deallocate(jni_ids());
2715   set_jni_ids(NULL);
2716 
2717   jmethodID* jmeths = methods_jmethod_ids_acquire();
2718   if (jmeths != (jmethodID*)NULL) {
2719     release_set_methods_jmethod_ids(NULL);
2720     FreeHeap(jmeths);
2721   }
2722 
2723   assert(_dep_context == NULL,
2724          "dependencies should already be cleaned");
2725 
2726 #if INCLUDE_JVMTI
2727   // Deallocate breakpoint records
2728   if (breakpoints() != 0x0) {
2729     methods_do(clear_all_breakpoints);
2730     assert(breakpoints() == 0x0, "should have cleared breakpoints");
2731   }
2732 
2733   // deallocate the cached class file
2734   if (_cached_class_file != NULL) {
2735     os::free(_cached_class_file);
2736     _cached_class_file = NULL;
2737   }
2738 #endif
2739 
2740   FREE_C_HEAP_ARRAY(char, _source_debug_extension);
2741 }
2742 
2743 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
2744   if (array == NULL) {
2745     _source_debug_extension = NULL;
2746   } else {
2747     // Adding one to the attribute length in order to store a null terminator
2748     // character could cause an overflow because the attribute length is
2749     // already coded with an u4 in the classfile, but in practice, it's
2750     // unlikely to happen.
2751     assert((length+1) > length, "Overflow checking");
2752     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2753     for (int i = 0; i < length; i++) {
2754       sde[i] = array[i];
2755     }
2756     sde[length] = '\0';
2757     _source_debug_extension = sde;
2758   }
2759 }
2760 
2761 const char* InstanceKlass::signature_name() const {




2762   int hash_len = 0;
2763   char hash_buf[40];
2764 
2765   // Get the internal name as a c string
2766   const char* src = (const char*) (name()->as_C_string());
2767   const int src_length = (int)strlen(src);
2768 
2769   char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
2770 
2771   // Add L as type indicator
2772   int dest_index = 0;
2773   dest[dest_index++] = JVM_SIGNATURE_CLASS;
2774 
2775   // Add the actual class name
2776   for (int src_index = 0; src_index < src_length; ) {
2777     dest[dest_index++] = src[src_index++];
2778   }
2779 
2780   if (is_hidden()) { // Replace the last '+' with a '.'.
2781     for (int index = (int)src_length; index > 0; index--) {
2782       if (dest[index] == '+') {
2783         dest[index] = JVM_SIGNATURE_DOT;
2784         break;
2785       }
2786     }
2787   }
2788 
2789   // If we have a hash, append it
2790   for (int hash_index = 0; hash_index < hash_len; ) {
2791     dest[dest_index++] = hash_buf[hash_index++];
2792   }
2793 
2794   // Add the semicolon and the NULL
2795   dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
2796   dest[dest_index] = '\0';
2797   return dest;
2798 }
2799 
2800 ModuleEntry* InstanceKlass::module() const {
2801   if (is_hidden() &&
2802       in_unnamed_package() &&
2803       class_loader_data()->has_class_mirror_holder()) {
2804     // For a non-strong hidden class defined to an unnamed package,
2805     // its (class held) CLD will not have an unnamed module created for it.
2806     // Two choices to find the correct ModuleEntry:
2807     // 1. If hidden class is within a nest, use nest host's module
2808     // 2. Find the unnamed module off from the class loader
2809     // For now option #2 is used since a nest host is not set until
2810     // after the instance class is created in jvm_lookup_define_class().
2811     if (class_loader_data()->is_boot_class_loader_data()) {
2812       return ClassLoaderData::the_null_class_loader_data()->unnamed_module();
2813     } else {
2814       oop module = java_lang_ClassLoader::unnamedModule(class_loader_data()->class_loader());
2815       assert(java_lang_Module::is_instance(module), "Not an instance of java.lang.Module");
2816       return java_lang_Module::module_entry(module);
2817     }
2818   }
2819 
2820   // Class is in a named package
2821   if (!in_unnamed_package()) {
2822     return _package_entry->module();
2823   }
2824 
2825   // Class is in an unnamed package, return its loader's unnamed module
2826   return class_loader_data()->unnamed_module();
2827 }
2828 
2829 void InstanceKlass::set_package(ClassLoaderData* loader_data, PackageEntry* pkg_entry, TRAPS) {
2830 
2831   // ensure java/ packages only loaded by boot or platform builtin loaders
2832   // not needed for shared class since CDS does not archive prohibited classes.
2833   if (!is_shared()) {
2834     check_prohibited_package(name(), loader_data, CHECK);
2835   }
2836 
2837   if (is_shared() && _package_entry != NULL) {
2838     if (MetaspaceShared::use_full_module_graph() && _package_entry == pkg_entry) {
2839       // we can use the saved package
2840       assert(MetaspaceShared::is_in_shared_metaspace(_package_entry), "must be");
2841       return;
2842     } else {
2843       _package_entry = NULL;
2844     }
2845   }
2846 
2847   // ClassLoader::package_from_class_name has already incremented the refcount of the symbol
2848   // it returns, so we need to decrement it when the current function exits.
2849   TempNewSymbol from_class_name =
2850       (pkg_entry != NULL) ? NULL : ClassLoader::package_from_class_name(name());
2851 
2852   Symbol* pkg_name;
2853   if (pkg_entry != NULL) {
2854     pkg_name = pkg_entry->name();
2855   } else {
2856     pkg_name = from_class_name;
2857   }
2858 
2859   if (pkg_name != NULL && loader_data != NULL) {
2860 
2861     // Find in class loader's package entry table.
2862     _package_entry = pkg_entry != NULL ? pkg_entry : loader_data->packages()->lookup_only(pkg_name);
2863 
2864     // If the package name is not found in the loader's package
2865     // entry table, it is an indication that the package has not
2866     // been defined. Consider it defined within the unnamed module.
2867     if (_package_entry == NULL) {
2868 
2869       if (!ModuleEntryTable::javabase_defined()) {
2870         // Before java.base is defined during bootstrapping, define all packages in
2871         // the java.base module.  If a non-java.base package is erroneously placed
2872         // in the java.base module it will be caught later when java.base
2873         // is defined by ModuleEntryTable::verify_javabase_packages check.
2874         assert(ModuleEntryTable::javabase_moduleEntry() != NULL, JAVA_BASE_NAME " module is NULL");
2875         _package_entry = loader_data->packages()->lookup(pkg_name, ModuleEntryTable::javabase_moduleEntry());
2876       } else {
2877         assert(loader_data->unnamed_module() != NULL, "unnamed module is NULL");
2878         _package_entry = loader_data->packages()->lookup(pkg_name,
2879                                                          loader_data->unnamed_module());
2880       }
2881 
2882       // A package should have been successfully created
2883       DEBUG_ONLY(ResourceMark rm(THREAD));
2884       assert(_package_entry != NULL, "Package entry for class %s not found, loader %s",
2885              name()->as_C_string(), loader_data->loader_name_and_id());
2886     }
2887 
2888     if (log_is_enabled(Debug, module)) {
2889       ResourceMark rm(THREAD);
2890       ModuleEntry* m = _package_entry->module();
2891       log_trace(module)("Setting package: class: %s, package: %s, loader: %s, module: %s",
2892                         external_name(),
2893                         pkg_name->as_C_string(),
2894                         loader_data->loader_name_and_id(),
2895                         (m->is_named() ? m->name()->as_C_string() : UNNAMED_MODULE));
2896     }
2897   } else {
2898     ResourceMark rm(THREAD);
2899     log_trace(module)("Setting package: class: %s, package: unnamed, loader: %s, module: %s",
2900                       external_name(),
2901                       (loader_data != NULL) ? loader_data->loader_name_and_id() : "NULL",
2902                       UNNAMED_MODULE);
2903   }
2904 }
2905 
2906 // Function set_classpath_index ensures that for a non-null _package_entry
2907 // of the InstanceKlass, the entry is in the boot loader's package entry table.
2908 // It then sets the classpath_index in the package entry record.
2909 //
2910 // The classpath_index field is used to find the entry on the boot loader class
2911 // path for packages with classes loaded by the boot loader from -Xbootclasspath/a
2912 // in an unnamed module.  It is also used to indicate (for all packages whose
2913 // classes are loaded by the boot loader) that at least one of the package's
2914 // classes has been loaded.
2915 void InstanceKlass::set_classpath_index(s2 path_index) {
2916   if (_package_entry != NULL) {
2917     DEBUG_ONLY(PackageEntryTable* pkg_entry_tbl = ClassLoaderData::the_null_class_loader_data()->packages();)
2918     assert(pkg_entry_tbl->lookup_only(_package_entry->name()) == _package_entry, "Should be same");
2919     assert(path_index != -1, "Unexpected classpath_index");
2920     _package_entry->set_classpath_index(path_index);
2921   }
2922 }
2923 
2924 // different versions of is_same_class_package
2925 
2926 bool InstanceKlass::is_same_class_package(const Klass* class2) const {
2927   oop classloader1 = this->class_loader();
2928   PackageEntry* classpkg1 = this->package();
2929   if (class2->is_objArray_klass()) {
2930     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
2931   }
2932 
2933   oop classloader2;
2934   PackageEntry* classpkg2;
2935   if (class2->is_instance_klass()) {
2936     classloader2 = class2->class_loader();
2937     classpkg2 = class2->package();
2938   } else {
2939     assert(class2->is_typeArray_klass(), "should be type array");
2940     classloader2 = NULL;
2941     classpkg2 = NULL;
2942   }
2943 
2944   // Same package is determined by comparing class loader
2945   // and package entries. Both must be the same. This rule
2946   // applies even to classes that are defined in the unnamed
2947   // package, they still must have the same class loader.
2948   if ((classloader1 == classloader2) && (classpkg1 == classpkg2)) {
2949     return true;
2950   }
2951 
2952   return false;
2953 }
2954 
2955 // return true if this class and other_class are in the same package. Classloader
2956 // and classname information is enough to determine a class's package
2957 bool InstanceKlass::is_same_class_package(oop other_class_loader,
2958                                           const Symbol* other_class_name) const {
2959   if (class_loader() != other_class_loader) {
2960     return false;
2961   }
2962   if (name()->fast_compare(other_class_name) == 0) {
2963      return true;
2964   }
2965 
2966   {
2967     ResourceMark rm;
2968 
2969     bool bad_class_name = false;
2970     TempNewSymbol other_pkg = ClassLoader::package_from_class_name(other_class_name, &bad_class_name);
2971     if (bad_class_name) {
2972       return false;
2973     }
2974     // Check that package_from_class_name() returns NULL, not "", if there is no package.
2975     assert(other_pkg == NULL || other_pkg->utf8_length() > 0, "package name is empty string");
2976 
2977     const Symbol* const this_package_name =
2978       this->package() != NULL ? this->package()->name() : NULL;
2979 
2980     if (this_package_name == NULL || other_pkg == NULL) {
2981       // One of the two doesn't have a package.  Only return true if the other
2982       // one also doesn't have a package.
2983       return this_package_name == other_pkg;
2984     }
2985 
2986     // Check if package is identical
2987     return this_package_name->fast_compare(other_pkg) == 0;
2988   }
2989 }
2990 
2991 static bool is_prohibited_package_slow(Symbol* class_name) {
2992   // Caller has ResourceMark
2993   int length;
2994   jchar* unicode = class_name->as_unicode(length);
2995   return (length >= 5 &&
2996           unicode[0] == 'j' &&
2997           unicode[1] == 'a' &&
2998           unicode[2] == 'v' &&
2999           unicode[3] == 'a' &&
3000           unicode[4] == '/');
3001 }
3002 
3003 // Only boot and platform class loaders can define classes in "java/" packages.
3004 void InstanceKlass::check_prohibited_package(Symbol* class_name,
3005                                              ClassLoaderData* loader_data,
3006                                              TRAPS) {
3007   if (!loader_data->is_boot_class_loader_data() &&
3008       !loader_data->is_platform_class_loader_data() &&
3009       class_name != NULL && class_name->utf8_length() >= 5) {
3010     ResourceMark rm(THREAD);
3011     bool prohibited;
3012     const u1* base = class_name->base();
3013     if ((base[0] | base[1] | base[2] | base[3] | base[4]) & 0x80) {
3014       prohibited = is_prohibited_package_slow(class_name);
3015     } else {
3016       char* name = class_name->as_C_string();
3017       prohibited = (strncmp(name, JAVAPKG, JAVAPKG_LEN) == 0 && name[JAVAPKG_LEN] == '/');
3018     }
3019     if (prohibited) {
3020       TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name);
3021       assert(pkg_name != NULL, "Error in parsing package name starting with 'java/'");
3022       char* name = pkg_name->as_C_string();
3023       const char* class_loader_name = loader_data->loader_name_and_id();
3024       StringUtils::replace_no_expand(name, "/", ".");
3025       const char* msg_text1 = "Class loader (instance of): ";
3026       const char* msg_text2 = " tried to load prohibited package name: ";
3027       size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + strlen(name) + 1;
3028       char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len);
3029       jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, name);
3030       THROW_MSG(vmSymbols::java_lang_SecurityException(), message);
3031     }
3032   }
3033   return;
3034 }
3035 
3036 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3037   constantPoolHandle i_cp(THREAD, constants());
3038   for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3039     int ioff = iter.inner_class_info_index();
3040     if (ioff != 0) {
3041       // Check to see if the name matches the class we're looking for
3042       // before attempting to find the class.
3043       if (i_cp->klass_name_at_matches(this, ioff)) {
3044         Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3045         if (this == inner_klass) {
3046           *ooff = iter.outer_class_info_index();
3047           *noff = iter.inner_name_index();
3048           return true;
3049         }
3050       }
3051     }
3052   }
3053   return false;
3054 }
3055 
3056 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3057   InstanceKlass* outer_klass = NULL;
3058   *inner_is_member = false;
3059   int ooff = 0, noff = 0;
3060   bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3061   if (has_inner_classes_attr) {
3062     constantPoolHandle i_cp(THREAD, constants());
3063     if (ooff != 0) {
3064       Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3065       outer_klass = InstanceKlass::cast(ok);
3066       *inner_is_member = true;
3067     }
3068     if (NULL == outer_klass) {
3069       // It may be a local class; try for that.
3070       int encl_method_class_idx = enclosing_method_class_index();
3071       if (encl_method_class_idx != 0) {
3072         Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
3073         outer_klass = InstanceKlass::cast(ok);
3074         *inner_is_member = false;
3075       }
3076     }
3077   }
3078 
3079   // If no inner class attribute found for this class.
3080   if (NULL == outer_klass) return NULL;
3081 
3082   // Throws an exception if outer klass has not declared k as an inner klass
3083   // We need evidence that each klass knows about the other, or else
3084   // the system could allow a spoof of an inner class to gain access rights.
3085   Reflection::check_for_inner_class(outer_klass, this, *inner_is_member, CHECK_NULL);
3086   return outer_klass;
3087 }
3088 
3089 jint InstanceKlass::compute_modifier_flags() const {
3090   jint access = access_flags().as_int();
3091 
3092   // But check if it happens to be member class.
3093   InnerClassesIterator iter(this);
3094   for (; !iter.done(); iter.next()) {
3095     int ioff = iter.inner_class_info_index();
3096     // Inner class attribute can be zero, skip it.
3097     // Strange but true:  JVM spec. allows null inner class refs.
3098     if (ioff == 0) continue;
3099 
3100     // only look at classes that are already loaded
3101     // since we are looking for the flags for our self.
3102     Symbol* inner_name = constants()->klass_name_at(ioff);
3103     if (name() == inner_name) {
3104       // This is really a member class.
3105       access = iter.inner_access_flags();
3106       break;
3107     }
3108   }
3109   // Remember to strip ACC_SUPER bit
3110   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
3111 }
3112 
3113 jint InstanceKlass::jvmti_class_status() const {
3114   jint result = 0;
3115 
3116   if (is_linked()) {
3117     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3118   }
3119 
3120   if (is_initialized()) {
3121     assert(is_linked(), "Class status is not consistent");
3122     result |= JVMTI_CLASS_STATUS_INITIALIZED;
3123   }
3124   if (is_in_error_state()) {
3125     result |= JVMTI_CLASS_STATUS_ERROR;
3126   }
3127   return result;
3128 }
3129 
3130 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
3131   bool implements_interface; // initialized by method_at_itable_or_null
3132   Method* m = method_at_itable_or_null(holder, index,
3133                                        implements_interface); // out parameter
3134   if (m != NULL) {
3135     assert(implements_interface, "sanity");
3136     return m;
3137   } else if (implements_interface) {
3138     // Throw AbstractMethodError since corresponding itable slot is empty.
3139     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
3140   } else {
3141     // If the interface isn't implemented by the receiver class,
3142     // the VM should throw IncompatibleClassChangeError.
3143     ResourceMark rm(THREAD);
3144     stringStream ss;
3145     bool same_module = (module() == holder->module());
3146     ss.print("Receiver class %s does not implement "
3147              "the interface %s defining the method to be called "
3148              "(%s%s%s)",
3149              external_name(), holder->external_name(),
3150              (same_module) ? joint_in_module_of_loader(holder) : class_in_module_of_loader(),
3151              (same_module) ? "" : "; ",
3152              (same_module) ? "" : holder->class_in_module_of_loader());
3153     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
3154   }
3155 }
3156 
3157 Method* InstanceKlass::method_at_itable_or_null(InstanceKlass* holder, int index, bool& implements_interface) {
3158   klassItable itable(this);
3159   for (int i = 0; i < itable.size_offset_table(); i++) {
3160     itableOffsetEntry* offset_entry = itable.offset_entry(i);
3161     if (offset_entry->interface_klass() == holder) {
3162       implements_interface = true;
3163       itableMethodEntry* ime = offset_entry->first_method_entry(this);
3164       Method* m = ime[index].method();
3165       return m;
3166     }
3167   }
3168   implements_interface = false;
3169   return NULL; // offset entry not found
3170 }
3171 
3172 int InstanceKlass::vtable_index_of_interface_method(Method* intf_method) {
3173   assert(is_linked(), "required");
3174   assert(intf_method->method_holder()->is_interface(), "not an interface method");
3175   assert(is_subtype_of(intf_method->method_holder()), "interface not implemented");
3176 
3177   int vtable_index = Method::invalid_vtable_index;
3178   Symbol* name = intf_method->name();
3179   Symbol* signature = intf_method->signature();
3180 
3181   // First check in default method array
3182   if (!intf_method->is_abstract() && default_methods() != NULL) {
3183     int index = find_method_index(default_methods(),
3184                                   name, signature,
3185                                   Klass::OverpassLookupMode::find,
3186                                   Klass::StaticLookupMode::find,
3187                                   Klass::PrivateLookupMode::find);
3188     if (index >= 0) {
3189       vtable_index = default_vtable_indices()->at(index);
3190     }
3191   }
3192   if (vtable_index == Method::invalid_vtable_index) {
3193     // get vtable_index for miranda methods
3194     klassVtable vt = vtable();
3195     vtable_index = vt.index_of_miranda(name, signature);
3196   }
3197   return vtable_index;
3198 }
3199 
3200 #if INCLUDE_JVMTI
3201 // update default_methods for redefineclasses for methods that are
3202 // not yet in the vtable due to concurrent subclass define and superinterface
3203 // redefinition
3204 // Note: those in the vtable, should have been updated via adjust_method_entries
3205 void InstanceKlass::adjust_default_methods(bool* trace_name_printed) {
3206   // search the default_methods for uses of either obsolete or EMCP methods
3207   if (default_methods() != NULL) {
3208     for (int index = 0; index < default_methods()->length(); index ++) {
3209       Method* old_method = default_methods()->at(index);
3210       if (old_method == NULL || !old_method->is_old()) {
3211         continue; // skip uninteresting entries
3212       }
3213       assert(!old_method->is_deleted(), "default methods may not be deleted");
3214       Method* new_method = old_method->get_new_method();
3215       default_methods()->at_put(index, new_method);
3216 
3217       if (log_is_enabled(Info, redefine, class, update)) {
3218         ResourceMark rm;
3219         if (!(*trace_name_printed)) {
3220           log_info(redefine, class, update)
3221             ("adjust: klassname=%s default methods from name=%s",
3222              external_name(), old_method->method_holder()->external_name());
3223           *trace_name_printed = true;
3224         }
3225         log_debug(redefine, class, update, vtables)
3226           ("default method update: %s(%s) ",
3227            new_method->name()->as_C_string(), new_method->signature()->as_C_string());
3228       }
3229     }
3230   }
3231 }
3232 #endif // INCLUDE_JVMTI
3233 
3234 // On-stack replacement stuff
3235 void InstanceKlass::add_osr_nmethod(nmethod* n) {
3236   assert_lock_strong(CompiledMethod_lock);
3237 #ifndef PRODUCT
3238   nmethod* prev = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), n->comp_level(), true);
3239   assert(prev == NULL || !prev->is_in_use() COMPILER2_PRESENT(|| StressRecompilation),
3240       "redundant OSR recompilation detected. memory leak in CodeCache!");
3241 #endif
3242   // only one compilation can be active
3243   assert(n->is_osr_method(), "wrong kind of nmethod");
3244   n->set_osr_link(osr_nmethods_head());
3245   set_osr_nmethods_head(n);
3246   // Raise the highest osr level if necessary
3247   n->method()->set_highest_osr_comp_level(MAX2(n->method()->highest_osr_comp_level(), n->comp_level()));
3248 
3249   // Get rid of the osr methods for the same bci that have lower levels.
3250   for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
3251     nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
3252     if (inv != NULL && inv->is_in_use()) {
3253       inv->make_not_entrant();
3254     }
3255   }
3256 }
3257 
3258 // Remove osr nmethod from the list. Return true if found and removed.
3259 bool InstanceKlass::remove_osr_nmethod(nmethod* n) {
3260   // This is a short non-blocking critical region, so the no safepoint check is ok.
3261   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock
3262                  , Mutex::_no_safepoint_check_flag);
3263   assert(n->is_osr_method(), "wrong kind of nmethod");
3264   nmethod* last = NULL;
3265   nmethod* cur  = osr_nmethods_head();
3266   int max_level = CompLevel_none;  // Find the max comp level excluding n
3267   Method* m = n->method();
3268   // Search for match
3269   bool found = false;
3270   while(cur != NULL && cur != n) {
3271     if (m == cur->method()) {
3272       // Find max level before n
3273       max_level = MAX2(max_level, cur->comp_level());
3274     }
3275     last = cur;
3276     cur = cur->osr_link();
3277   }
3278   nmethod* next = NULL;
3279   if (cur == n) {
3280     found = true;
3281     next = cur->osr_link();
3282     if (last == NULL) {
3283       // Remove first element
3284       set_osr_nmethods_head(next);
3285     } else {
3286       last->set_osr_link(next);
3287     }
3288   }
3289   n->set_osr_link(NULL);
3290   cur = next;
3291   while (cur != NULL) {
3292     // Find max level after n
3293     if (m == cur->method()) {
3294       max_level = MAX2(max_level, cur->comp_level());
3295     }
3296     cur = cur->osr_link();
3297   }
3298   m->set_highest_osr_comp_level(max_level);
3299   return found;
3300 }
3301 
3302 int InstanceKlass::mark_osr_nmethods(const Method* m) {
3303   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock,
3304                  Mutex::_no_safepoint_check_flag);
3305   nmethod* osr = osr_nmethods_head();
3306   int found = 0;
3307   while (osr != NULL) {
3308     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3309     if (osr->method() == m) {
3310       osr->mark_for_deoptimization();
3311       found++;
3312     }
3313     osr = osr->osr_link();
3314   }
3315   return found;
3316 }
3317 
3318 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
3319   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock,
3320                  Mutex::_no_safepoint_check_flag);
3321   nmethod* osr = osr_nmethods_head();
3322   nmethod* best = NULL;
3323   while (osr != NULL) {
3324     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3325     // There can be a time when a c1 osr method exists but we are waiting
3326     // for a c2 version. When c2 completes its osr nmethod we will trash
3327     // the c1 version and only be able to find the c2 version. However
3328     // while we overflow in the c1 code at back branches we don't want to
3329     // try and switch to the same code as we are already running
3330 
3331     if (osr->method() == m &&
3332         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
3333       if (match_level) {
3334         if (osr->comp_level() == comp_level) {
3335           // Found a match - return it.
3336           return osr;
3337         }
3338       } else {
3339         if (best == NULL || (osr->comp_level() > best->comp_level())) {
3340           if (osr->comp_level() == CompilationPolicy::highest_compile_level()) {
3341             // Found the best possible - return it.
3342             return osr;
3343           }
3344           best = osr;
3345         }
3346       }
3347     }
3348     osr = osr->osr_link();
3349   }
3350 
3351   assert(match_level == false || best == NULL, "shouldn't pick up anything if match_level is set");
3352   if (best != NULL && best->comp_level() >= comp_level) {
3353     return best;
3354   }
3355   return NULL;
3356 }
3357 
3358 // -----------------------------------------------------------------------------------------------------
3359 // Printing
3360 
3361 #define BULLET  " - "
3362 
3363 static const char* state_names[] = {
3364   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3365 };
3366 
3367 static void print_vtable(intptr_t* start, int len, outputStream* st) {



3368   for (int i = 0; i < len; i++) {
3369     intptr_t e = start[i];
3370     st->print("%d : " INTPTR_FORMAT, i, e);





3371     if (MetaspaceObj::is_valid((Metadata*)e)) {
3372       st->print(" ");
3373       ((Metadata*)e)->print_value_on(st);






3374     }
3375     st->cr();
3376   }
3377 }
3378 
3379 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3380   return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);





















3381 }
3382 
3383 void InstanceKlass::print_on(outputStream* st) const {
3384   assert(is_klass(), "must be klass");
3385   Klass::print_on(st);
3386 
3387   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3388   st->print(BULLET"klass size:        %d", size());                               st->cr();
3389   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();

3390   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
3391   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3392   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3393   st->print(BULLET"sub:               ");
3394   Klass* sub = subklass();
3395   int n;
3396   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
3397     if (n < MaxSubklassPrintSize) {
3398       sub->print_value_on(st);
3399       st->print("   ");
3400     }
3401   }
3402   if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize);
3403   st->cr();
3404 
3405   if (is_interface()) {
3406     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
3407     if (nof_implementors() == 1) {
3408       st->print_cr(BULLET"implementor:    ");
3409       st->print("   ");
3410       implementor()->print_value_on(st);
3411       st->cr();
3412     }
3413   }
3414 
3415   st->print(BULLET"arrays:            "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3416   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
3417   if (Verbose || WizardMode) {
3418     Array<Method*>* method_array = methods();
3419     for (int i = 0; i < method_array->length(); i++) {
3420       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3421     }
3422   }
3423   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
3424   st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
3425   if (Verbose && default_methods() != NULL) {
3426     Array<Method*>* method_array = default_methods();
3427     for (int i = 0; i < method_array->length(); i++) {
3428       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3429     }
3430   }
3431   if (default_vtable_indices() != NULL) {
3432     st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
3433   }
3434   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
3435   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3436   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
3437   if (class_loader_data() != NULL) {
3438     st->print(BULLET"class loader data:  ");
3439     class_loader_data()->print_value_on(st);
3440     st->cr();
3441   }
3442   if (source_file_name() != NULL) {
3443     st->print(BULLET"source file:       ");
3444     source_file_name()->print_value_on(st);
3445     st->cr();
3446   }
3447   if (source_debug_extension() != NULL) {
3448     st->print(BULLET"source debug extension:       ");
3449     st->print("%s", source_debug_extension());
3450     st->cr();
3451   }
3452   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
3453   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
3454   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
3455   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
3456   {
3457     bool have_pv = false;
3458     // previous versions are linked together through the InstanceKlass
3459     for (InstanceKlass* pv_node = previous_versions();
3460          pv_node != NULL;
3461          pv_node = pv_node->previous_versions()) {
3462       if (!have_pv)
3463         st->print(BULLET"previous version:  ");
3464       have_pv = true;
3465       pv_node->constants()->print_value_on(st);
3466     }
3467     if (have_pv) st->cr();
3468   }
3469 
3470   if (generic_signature() != NULL) {
3471     st->print(BULLET"generic signature: ");
3472     generic_signature()->print_value_on(st);
3473     st->cr();
3474   }
3475   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
3476   st->print(BULLET"nest members:     "); nest_members()->print_value_on(st);     st->cr();
3477   if (record_components() != NULL) {
3478     st->print(BULLET"record components:     "); record_components()->print_value_on(st);     st->cr();
3479   }
3480   st->print(BULLET"permitted subclasses:     "); permitted_subclasses()->print_value_on(st);     st->cr();
3481   if (java_mirror() != NULL) {
3482     st->print(BULLET"java mirror:       ");
3483     java_mirror()->print_value_on(st);
3484     st->cr();
3485   } else {
3486     st->print_cr(BULLET"java mirror:       NULL");
3487   }
3488   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3489   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
3490   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3491   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
3492   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3493   FieldPrinter print_static_field(st);
3494   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3495   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3496   FieldPrinter print_nonstatic_field(st);
3497   InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3498   ik->print_nonstatic_fields(&print_nonstatic_field);
3499 
3500   st->print(BULLET"non-static oop maps: ");
3501   OopMapBlock* map     = start_of_nonstatic_oop_maps();
3502   OopMapBlock* end_map = map + nonstatic_oop_map_count();
3503   while (map < end_map) {
3504     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3505     map++;
3506   }
3507   st->cr();
3508 }
3509 
3510 void InstanceKlass::print_value_on(outputStream* st) const {
3511   assert(is_klass(), "must be klass");
3512   if (Verbose || WizardMode)  access_flags().print_on(st);
3513   name()->print_value_on(st);
3514 }
3515 
3516 void FieldPrinter::do_field(fieldDescriptor* fd) {
3517   _st->print(BULLET);
3518    if (_obj == NULL) {
3519      fd->print_on(_st);
3520      _st->cr();
3521    } else {
3522      fd->print_on_for(_st, _obj);
3523      _st->cr();
3524    }
3525 }
3526 
3527 
3528 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3529   Klass::oop_print_on(obj, st);
3530 
3531   if (this == vmClasses::String_klass()) {
3532     typeArrayOop value  = java_lang_String::value(obj);
3533     juint        length = java_lang_String::length(obj);
3534     if (value != NULL &&
3535         value->is_typeArray() &&
3536         length <= (juint) value->length()) {
3537       st->print(BULLET"string: ");
3538       java_lang_String::print(obj, st);
3539       st->cr();
3540     }
3541   }
3542 
3543   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
3544   FieldPrinter print_field(st, obj);
3545   print_nonstatic_fields(&print_field);
3546 
3547   if (this == vmClasses::Class_klass()) {
3548     st->print(BULLET"signature: ");
3549     java_lang_Class::print_signature(obj, st);
3550     st->cr();
3551     Klass* real_klass = java_lang_Class::as_Klass(obj);
3552     if (real_klass != NULL && real_klass->is_instance_klass()) {
3553       st->print_cr(BULLET"---- static fields (%d words):", java_lang_Class::static_oop_field_count(obj));
3554       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3555     }
3556   } else if (this == vmClasses::MethodType_klass()) {
3557     st->print(BULLET"signature: ");
3558     java_lang_invoke_MethodType::print_signature(obj, st);
3559     st->cr();
3560   }
3561 }
3562 
3563 #ifndef PRODUCT
3564 
3565 bool InstanceKlass::verify_itable_index(int i) {
3566   int method_count = klassItable::method_count_for_interface(this);
3567   assert(i >= 0 && i < method_count, "index out of bounds");
3568   return true;
3569 }
3570 
3571 #endif //PRODUCT
3572 
3573 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
3574   st->print("a ");
3575   name()->print_value_on(st);
3576   obj->print_address_on(st);
3577   if (this == vmClasses::String_klass()
3578       && java_lang_String::value(obj) != NULL) {
3579     ResourceMark rm;
3580     int len = java_lang_String::length(obj);
3581     int plen = (len < 24 ? len : 12);
3582     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
3583     st->print(" = \"%s\"", str);
3584     if (len > plen)
3585       st->print("...[%d]", len);
3586   } else if (this == vmClasses::Class_klass()) {
3587     Klass* k = java_lang_Class::as_Klass(obj);
3588     st->print(" = ");
3589     if (k != NULL) {
3590       k->print_value_on(st);
3591     } else {
3592       const char* tname = type2name(java_lang_Class::primitive_type(obj));
3593       st->print("%s", tname ? tname : "type?");
3594     }
3595   } else if (this == vmClasses::MethodType_klass()) {
3596     st->print(" = ");
3597     java_lang_invoke_MethodType::print_signature(obj, st);
3598   } else if (java_lang_boxing_object::is_instance(obj)) {
3599     st->print(" = ");
3600     java_lang_boxing_object::print(obj, st);
3601   } else if (this == vmClasses::LambdaForm_klass()) {
3602     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
3603     if (vmentry != NULL) {
3604       st->print(" => ");
3605       vmentry->print_value_on(st);
3606     }
3607   } else if (this == vmClasses::MemberName_klass()) {
3608     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
3609     if (vmtarget != NULL) {
3610       st->print(" = ");
3611       vmtarget->print_value_on(st);
3612     } else {
3613       oop clazz = java_lang_invoke_MemberName::clazz(obj);
3614       oop name  = java_lang_invoke_MemberName::name(obj);
3615       if (clazz != NULL) {
3616         clazz->print_value_on(st);
3617       } else {
3618         st->print("NULL");
3619       }
3620       st->print(".");
3621       if (name != NULL) {
3622         name->print_value_on(st);
3623       } else {
3624         st->print("NULL");
3625       }
3626     }
3627   }
3628 }
3629 
3630 const char* InstanceKlass::internal_name() const {
3631   return external_name();
3632 }
3633 
3634 void InstanceKlass::print_class_load_logging(ClassLoaderData* loader_data,
3635                                              const ModuleEntry* module_entry,
3636                                              const ClassFileStream* cfs) const {
3637   if (ClassListWriter::is_enabled()) {
3638     ClassListWriter::write(this, cfs);
3639   }
3640 
3641   if (!log_is_enabled(Info, class, load)) {
3642     return;
3643   }
3644 
3645   ResourceMark rm;
3646   LogMessage(class, load) msg;
3647   stringStream info_stream;
3648 
3649   // Name and class hierarchy info
3650   info_stream.print("%s", external_name());
3651 
3652   // Source
3653   if (cfs != NULL) {
3654     if (cfs->source() != NULL) {
3655       const char* module_name = (module_entry->name() == NULL) ? UNNAMED_MODULE : module_entry->name()->as_C_string();
3656       if (module_name != NULL) {
3657         // When the boot loader created the stream, it didn't know the module name
3658         // yet. Let's format it now.
3659         if (cfs->from_boot_loader_modules_image()) {
3660           info_stream.print(" source: jrt:/%s", module_name);
3661         } else {
3662           info_stream.print(" source: %s", cfs->source());
3663         }
3664       } else {
3665         info_stream.print(" source: %s", cfs->source());
3666       }
3667     } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) {
3668       Thread* current = Thread::current();
3669       Klass* caller = current->is_Java_thread() ?
3670         JavaThread::cast(current)->security_get_caller_class(1):
3671         NULL;
3672       // caller can be NULL, for example, during a JVMTI VM_Init hook
3673       if (caller != NULL) {
3674         info_stream.print(" source: instance of %s", caller->external_name());
3675       } else {
3676         // source is unknown
3677       }
3678     } else {
3679       oop class_loader = loader_data->class_loader();
3680       info_stream.print(" source: %s", class_loader->klass()->external_name());
3681     }
3682   } else {
3683     assert(this->is_shared(), "must be");
3684     if (MetaspaceShared::is_shared_dynamic((void*)this)) {
3685       info_stream.print(" source: shared objects file (top)");
3686     } else {
3687       info_stream.print(" source: shared objects file");
3688     }
3689   }
3690 
3691   msg.info("%s", info_stream.as_string());
3692 
3693   if (log_is_enabled(Debug, class, load)) {
3694     stringStream debug_stream;
3695 
3696     // Class hierarchy info
3697     debug_stream.print(" klass: " INTPTR_FORMAT " super: " INTPTR_FORMAT,
3698                        p2i(this),  p2i(superklass()));
3699 
3700     // Interfaces
3701     if (local_interfaces() != NULL && local_interfaces()->length() > 0) {
3702       debug_stream.print(" interfaces:");
3703       int length = local_interfaces()->length();
3704       for (int i = 0; i < length; i++) {
3705         debug_stream.print(" " INTPTR_FORMAT,
3706                            p2i(InstanceKlass::cast(local_interfaces()->at(i))));
3707       }
3708     }
3709 
3710     // Class loader
3711     debug_stream.print(" loader: [");
3712     loader_data->print_value_on(&debug_stream);
3713     debug_stream.print("]");
3714 
3715     // Classfile checksum
3716     if (cfs) {
3717       debug_stream.print(" bytes: %d checksum: %08x",
3718                          cfs->length(),
3719                          ClassLoader::crc32(0, (const char*)cfs->buffer(),
3720                          cfs->length()));
3721     }
3722 
3723     msg.debug("%s", debug_stream.as_string());
3724   }
3725 }
3726 
3727 // Verification
3728 
3729 class VerifyFieldClosure: public BasicOopIterateClosure {
3730  protected:
3731   template <class T> void do_oop_work(T* p) {
3732     oop obj = RawAccess<>::oop_load(p);
3733     if (!oopDesc::is_oop_or_null(obj)) {
3734       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj));
3735       Universe::print_on(tty);
3736       guarantee(false, "boom");
3737     }
3738   }
3739  public:
3740   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
3741   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
3742 };
3743 
3744 void InstanceKlass::verify_on(outputStream* st) {
3745 #ifndef PRODUCT
3746   // Avoid redundant verifies, this really should be in product.
3747   if (_verify_count == Universe::verify_count()) return;
3748   _verify_count = Universe::verify_count();
3749 #endif
3750 
3751   // Verify Klass
3752   Klass::verify_on(st);
3753 
3754   // Verify that klass is present in ClassLoaderData
3755   guarantee(class_loader_data()->contains_klass(this),
3756             "this class isn't found in class loader data");
3757 
3758   // Verify vtables
3759   if (is_linked()) {
3760     // $$$ This used to be done only for m/s collections.  Doing it
3761     // always seemed a valid generalization.  (DLD -- 6/00)
3762     vtable().verify(st);
3763   }
3764 
3765   // Verify first subklass
3766   if (subklass() != NULL) {
3767     guarantee(subklass()->is_klass(), "should be klass");
3768   }
3769 
3770   // Verify siblings
3771   Klass* super = this->super();
3772   Klass* sib = next_sibling();
3773   if (sib != NULL) {
3774     if (sib == this) {
3775       fatal("subclass points to itself " PTR_FORMAT, p2i(sib));
3776     }
3777 
3778     guarantee(sib->is_klass(), "should be klass");
3779     guarantee(sib->super() == super, "siblings should have same superklass");
3780   }
3781 
3782   // Verify local interfaces
3783   if (local_interfaces()) {
3784     Array<InstanceKlass*>* local_interfaces = this->local_interfaces();
3785     for (int j = 0; j < local_interfaces->length(); j++) {
3786       InstanceKlass* e = local_interfaces->at(j);
3787       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
3788     }
3789   }
3790 
3791   // Verify transitive interfaces
3792   if (transitive_interfaces() != NULL) {
3793     Array<InstanceKlass*>* transitive_interfaces = this->transitive_interfaces();
3794     for (int j = 0; j < transitive_interfaces->length(); j++) {
3795       InstanceKlass* e = transitive_interfaces->at(j);
3796       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
3797     }
3798   }
3799 
3800   // Verify methods
3801   if (methods() != NULL) {
3802     Array<Method*>* methods = this->methods();
3803     for (int j = 0; j < methods->length(); j++) {
3804       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3805     }
3806     for (int j = 0; j < methods->length() - 1; j++) {
3807       Method* m1 = methods->at(j);
3808       Method* m2 = methods->at(j + 1);
3809       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3810     }
3811   }
3812 
3813   // Verify method ordering
3814   if (method_ordering() != NULL) {
3815     Array<int>* method_ordering = this->method_ordering();
3816     int length = method_ordering->length();
3817     if (JvmtiExport::can_maintain_original_method_order() ||
3818         ((UseSharedSpaces || Arguments::is_dumping_archive()) && length != 0)) {
3819       guarantee(length == methods()->length(), "invalid method ordering length");
3820       jlong sum = 0;
3821       for (int j = 0; j < length; j++) {
3822         int original_index = method_ordering->at(j);
3823         guarantee(original_index >= 0, "invalid method ordering index");
3824         guarantee(original_index < length, "invalid method ordering index");
3825         sum += original_index;
3826       }
3827       // Verify sum of indices 0,1,...,length-1
3828       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
3829     } else {
3830       guarantee(length == 0, "invalid method ordering length");
3831     }
3832   }
3833 
3834   // Verify default methods
3835   if (default_methods() != NULL) {
3836     Array<Method*>* methods = this->default_methods();
3837     for (int j = 0; j < methods->length(); j++) {
3838       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3839     }
3840     for (int j = 0; j < methods->length() - 1; j++) {
3841       Method* m1 = methods->at(j);
3842       Method* m2 = methods->at(j + 1);
3843       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3844     }
3845   }
3846 
3847   // Verify JNI static field identifiers
3848   if (jni_ids() != NULL) {
3849     jni_ids()->verify(this);
3850   }
3851 
3852   // Verify other fields
3853   if (constants() != NULL) {
3854     guarantee(constants()->is_constantPool(), "should be constant pool");
3855   }
3856 }
3857 
3858 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
3859   Klass::oop_verify_on(obj, st);
3860   VerifyFieldClosure blk;
3861   obj->oop_iterate(&blk);
3862 }
3863 
3864 
3865 // JNIid class for jfieldIDs only
3866 // Note to reviewers:
3867 // These JNI functions are just moved over to column 1 and not changed
3868 // in the compressed oops workspace.
3869 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
3870   _holder = holder;
3871   _offset = offset;
3872   _next = next;
3873   debug_only(_is_static_field_id = false;)
3874 }
3875 
3876 
3877 JNIid* JNIid::find(int offset) {
3878   JNIid* current = this;
3879   while (current != NULL) {
3880     if (current->offset() == offset) return current;
3881     current = current->next();
3882   }
3883   return NULL;
3884 }
3885 
3886 void JNIid::deallocate(JNIid* current) {
3887   while (current != NULL) {
3888     JNIid* next = current->next();
3889     delete current;
3890     current = next;
3891   }
3892 }
3893 
3894 
3895 void JNIid::verify(Klass* holder) {
3896   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
3897   int end_field_offset;
3898   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
3899 
3900   JNIid* current = this;
3901   while (current != NULL) {
3902     guarantee(current->holder() == holder, "Invalid klass in JNIid");
3903 #ifdef ASSERT
3904     int o = current->offset();
3905     if (current->is_static_field_id()) {
3906       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
3907     }
3908 #endif
3909     current = current->next();
3910   }
3911 }
3912 
3913 void InstanceKlass::set_init_state(ClassState state) {
3914 #ifdef ASSERT
3915   bool good_state = is_shared() ? (_init_state <= state)
3916                                                : (_init_state < state);
3917   assert(good_state || state == allocated, "illegal state transition");
3918 #endif
3919   assert(_init_thread == NULL, "should be cleared before state change");
3920   _init_state = (u1)state;
3921 }
3922 
3923 #if INCLUDE_JVMTI
3924 
3925 // RedefineClasses() support for previous versions
3926 
3927 // Globally, there is at least one previous version of a class to walk
3928 // during class unloading, which is saved because old methods in the class
3929 // are still running.   Otherwise the previous version list is cleaned up.
3930 bool InstanceKlass::_has_previous_versions = false;
3931 
3932 // Returns true if there are previous versions of a class for class
3933 // unloading only. Also resets the flag to false. purge_previous_version
3934 // will set the flag to true if there are any left, i.e., if there's any
3935 // work to do for next time. This is to avoid the expensive code cache
3936 // walk in CLDG::clean_deallocate_lists().
3937 bool InstanceKlass::has_previous_versions_and_reset() {
3938   bool ret = _has_previous_versions;
3939   log_trace(redefine, class, iklass, purge)("Class unloading: has_previous_versions = %s",
3940      ret ? "true" : "false");
3941   _has_previous_versions = false;
3942   return ret;
3943 }
3944 
3945 // Purge previous versions before adding new previous versions of the class and
3946 // during class unloading.
3947 void InstanceKlass::purge_previous_version_list() {
3948   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
3949   assert(has_been_redefined(), "Should only be called for main class");
3950 
3951   // Quick exit.
3952   if (previous_versions() == NULL) {
3953     return;
3954   }
3955 
3956   // This klass has previous versions so see what we can cleanup
3957   // while it is safe to do so.
3958 
3959   int deleted_count = 0;    // leave debugging breadcrumbs
3960   int live_count = 0;
3961   ClassLoaderData* loader_data = class_loader_data();
3962   assert(loader_data != NULL, "should never be null");
3963 
3964   ResourceMark rm;
3965   log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name());
3966 
3967   // previous versions are linked together through the InstanceKlass
3968   InstanceKlass* pv_node = previous_versions();
3969   InstanceKlass* last = this;
3970   int version = 0;
3971 
3972   // check the previous versions list
3973   for (; pv_node != NULL; ) {
3974 
3975     ConstantPool* pvcp = pv_node->constants();
3976     assert(pvcp != NULL, "cp ref was unexpectedly cleared");
3977 
3978     if (!pvcp->on_stack()) {
3979       // If the constant pool isn't on stack, none of the methods
3980       // are executing.  Unlink this previous_version.
3981       // The previous version InstanceKlass is on the ClassLoaderData deallocate list
3982       // so will be deallocated during the next phase of class unloading.
3983       log_trace(redefine, class, iklass, purge)
3984         ("previous version " INTPTR_FORMAT " is dead.", p2i(pv_node));
3985       // For debugging purposes.
3986       pv_node->set_is_scratch_class();
3987       // Unlink from previous version list.
3988       assert(pv_node->class_loader_data() == loader_data, "wrong loader_data");
3989       InstanceKlass* next = pv_node->previous_versions();
3990       pv_node->link_previous_versions(NULL);   // point next to NULL
3991       last->link_previous_versions(next);
3992       // Delete this node directly. Nothing is referring to it and we don't
3993       // want it to increase the counter for metadata to delete in CLDG.
3994       MetadataFactory::free_metadata(loader_data, pv_node);
3995       pv_node = next;
3996       deleted_count++;
3997       version++;
3998       continue;
3999     } else {
4000       log_trace(redefine, class, iklass, purge)("previous version " INTPTR_FORMAT " is alive", p2i(pv_node));
4001       assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
4002       guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
4003       live_count++;
4004       // found a previous version for next time we do class unloading
4005       _has_previous_versions = true;
4006     }
4007 
4008     // next previous version
4009     last = pv_node;
4010     pv_node = pv_node->previous_versions();
4011     version++;
4012   }
4013   log_trace(redefine, class, iklass, purge)
4014     ("previous version stats: live=%d, deleted=%d", live_count, deleted_count);
4015 }
4016 
4017 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,
4018                                                 int emcp_method_count) {
4019   int obsolete_method_count = old_methods->length() - emcp_method_count;
4020 
4021   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
4022       _previous_versions != NULL) {
4023     // We have a mix of obsolete and EMCP methods so we have to
4024     // clear out any matching EMCP method entries the hard way.
4025     int local_count = 0;
4026     for (int i = 0; i < old_methods->length(); i++) {
4027       Method* old_method = old_methods->at(i);
4028       if (old_method->is_obsolete()) {
4029         // only obsolete methods are interesting
4030         Symbol* m_name = old_method->name();
4031         Symbol* m_signature = old_method->signature();
4032 
4033         // previous versions are linked together through the InstanceKlass
4034         int j = 0;
4035         for (InstanceKlass* prev_version = _previous_versions;
4036              prev_version != NULL;
4037              prev_version = prev_version->previous_versions(), j++) {
4038 
4039           Array<Method*>* method_refs = prev_version->methods();
4040           for (int k = 0; k < method_refs->length(); k++) {
4041             Method* method = method_refs->at(k);
4042 
4043             if (!method->is_obsolete() &&
4044                 method->name() == m_name &&
4045                 method->signature() == m_signature) {
4046               // The current RedefineClasses() call has made all EMCP
4047               // versions of this method obsolete so mark it as obsolete
4048               log_trace(redefine, class, iklass, add)
4049                 ("%s(%s): flush obsolete method @%d in version @%d",
4050                  m_name->as_C_string(), m_signature->as_C_string(), k, j);
4051 
4052               method->set_is_obsolete();
4053               break;
4054             }
4055           }
4056 
4057           // The previous loop may not find a matching EMCP method, but
4058           // that doesn't mean that we can optimize and not go any
4059           // further back in the PreviousVersion generations. The EMCP
4060           // method for this generation could have already been made obsolete,
4061           // but there still may be an older EMCP method that has not
4062           // been made obsolete.
4063         }
4064 
4065         if (++local_count >= obsolete_method_count) {
4066           // no more obsolete methods so bail out now
4067           break;
4068         }
4069       }
4070     }
4071   }
4072 }
4073 
4074 // Save the scratch_class as the previous version if any of the methods are running.
4075 // The previous_versions are used to set breakpoints in EMCP methods and they are
4076 // also used to clean MethodData links to redefined methods that are no longer running.
4077 void InstanceKlass::add_previous_version(InstanceKlass* scratch_class,
4078                                          int emcp_method_count) {
4079   assert(Thread::current()->is_VM_thread(),
4080          "only VMThread can add previous versions");
4081 
4082   ResourceMark rm;
4083   log_trace(redefine, class, iklass, add)
4084     ("adding previous version ref for %s, EMCP_cnt=%d", scratch_class->external_name(), emcp_method_count);
4085 
4086   // Clean out old previous versions for this class
4087   purge_previous_version_list();
4088 
4089   // Mark newly obsolete methods in remaining previous versions.  An EMCP method from
4090   // a previous redefinition may be made obsolete by this redefinition.
4091   Array<Method*>* old_methods = scratch_class->methods();
4092   mark_newly_obsolete_methods(old_methods, emcp_method_count);
4093 
4094   // If the constant pool for this previous version of the class
4095   // is not marked as being on the stack, then none of the methods
4096   // in this previous version of the class are on the stack so
4097   // we don't need to add this as a previous version.
4098   ConstantPool* cp_ref = scratch_class->constants();
4099   if (!cp_ref->on_stack()) {
4100     log_trace(redefine, class, iklass, add)("scratch class not added; no methods are running");
4101     // For debugging purposes.
4102     scratch_class->set_is_scratch_class();
4103     scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class);
4104     return;
4105   }
4106 
4107   // Add previous version if any methods are still running.
4108   // Set has_previous_version flag for processing during class unloading.
4109   _has_previous_versions = true;
4110   log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack.");
4111   assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");
4112   scratch_class->link_previous_versions(previous_versions());
4113   link_previous_versions(scratch_class);
4114 } // end add_previous_version()
4115 
4116 #endif // INCLUDE_JVMTI
4117 
4118 Method* InstanceKlass::method_with_idnum(int idnum) {
4119   Method* m = NULL;
4120   if (idnum < methods()->length()) {
4121     m = methods()->at(idnum);
4122   }
4123   if (m == NULL || m->method_idnum() != idnum) {
4124     for (int index = 0; index < methods()->length(); ++index) {
4125       m = methods()->at(index);
4126       if (m->method_idnum() == idnum) {
4127         return m;
4128       }
4129     }
4130     // None found, return null for the caller to handle.
4131     return NULL;
4132   }
4133   return m;
4134 }
4135 
4136 
4137 Method* InstanceKlass::method_with_orig_idnum(int idnum) {
4138   if (idnum >= methods()->length()) {
4139     return NULL;
4140   }
4141   Method* m = methods()->at(idnum);
4142   if (m != NULL && m->orig_method_idnum() == idnum) {
4143     return m;
4144   }
4145   // Obsolete method idnum does not match the original idnum
4146   for (int index = 0; index < methods()->length(); ++index) {
4147     m = methods()->at(index);
4148     if (m->orig_method_idnum() == idnum) {
4149       return m;
4150     }
4151   }
4152   // None found, return null for the caller to handle.
4153   return NULL;
4154 }
4155 
4156 
4157 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {
4158   InstanceKlass* holder = get_klass_version(version);
4159   if (holder == NULL) {
4160     return NULL; // The version of klass is gone, no method is found
4161   }
4162   Method* method = holder->method_with_orig_idnum(idnum);
4163   return method;
4164 }
4165 
4166 #if INCLUDE_JVMTI
4167 JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() {
4168   return _cached_class_file;
4169 }
4170 
4171 jint InstanceKlass::get_cached_class_file_len() {
4172   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
4173 }
4174 
4175 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
4176   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
4177 }
4178 #endif
4179 
4180 // Make a step iterating over the class hierarchy under the root class.
4181 // Skips subclasses if requested.
4182 void ClassHierarchyIterator::next() {
4183   assert(_current != NULL, "required");
4184   if (_visit_subclasses && _current->subklass() != NULL) {
4185     _current = _current->subklass();
4186     return; // visit next subclass
4187   }
4188   _visit_subclasses = true; // reset
4189   while (_current->next_sibling() == NULL && _current != _root) {
4190     _current = _current->superklass(); // backtrack; no more sibling subclasses left
4191   }
4192   if (_current == _root) {
4193     // Iteration is over (back at root after backtracking). Invalidate the iterator.
4194     _current = NULL;
4195     return;
4196   }
4197   _current = _current->next_sibling();
4198   return; // visit next sibling subclass
4199 }
--- EOF ---