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