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