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