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