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