1 /*
   2  * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "cds/archiveUtils.hpp"
  28 #include "cds/classListWriter.hpp"
  29 #include "cds/metaspaceShared.hpp"
  30 #include "classfile/classFileParser.hpp"
  31 #include "classfile/classFileStream.hpp"
  32 #include "classfile/classLoader.hpp"
  33 #include "classfile/classLoaderData.inline.hpp"
  34 #include "classfile/javaClasses.hpp"
  35 #include "classfile/moduleEntry.hpp"
  36 #include "classfile/resolutionErrors.hpp"
  37 #include "classfile/symbolTable.hpp"
  38 #include "classfile/systemDictionary.hpp"
  39 #include "classfile/systemDictionaryShared.hpp"
  40 #include "classfile/verifier.hpp"
  41 #include "classfile/vmClasses.hpp"
  42 #include "classfile/vmSymbols.hpp"
  43 #include "code/codeCache.hpp"
  44 #include "code/dependencyContext.hpp"
  45 #include "compiler/compilationPolicy.hpp"
  46 #include "compiler/compileBroker.hpp"
  47 #include "gc/shared/collectedHeap.inline.hpp"
  48 #include "interpreter/oopMapCache.hpp"
  49 #include "interpreter/rewriter.hpp"
  50 #include "jvmtifiles/jvmti.h"
  51 #include "logging/log.hpp"
  52 #include "logging/logMessage.hpp"
  53 #include "logging/logStream.hpp"
  54 #include "memory/allocation.inline.hpp"
  55 #include "memory/iterator.inline.hpp"
  56 #include "memory/metadataFactory.hpp"
  57 #include "memory/metaspaceClosure.hpp"
  58 #include "memory/oopFactory.hpp"
  59 #include "memory/resourceArea.hpp"
  60 #include "memory/universe.hpp"
  61 #include "oops/fieldStreams.inline.hpp"
  62 #include "oops/constantPool.hpp"
  63 #include "oops/instanceClassLoaderKlass.hpp"
  64 #include "oops/instanceKlass.inline.hpp"
  65 #include "oops/instanceMirrorKlass.hpp"
  66 #include "oops/instanceOop.hpp"
  67 #include "oops/klass.inline.hpp"
  68 #include "oops/method.hpp"
  69 #include "oops/oop.inline.hpp"
  70 #include "oops/recordComponent.hpp"
  71 #include "oops/symbol.hpp"
  72 #include "oops/inlineKlass.hpp"
  73 #include "prims/jvmtiExport.hpp"
  74 #include "prims/jvmtiRedefineClasses.hpp"
  75 #include "prims/jvmtiThreadState.hpp"
  76 #include "prims/methodComparator.hpp"
  77 #include "runtime/arguments.hpp"
  78 #include "runtime/atomic.hpp"
  79 #include "runtime/fieldDescriptor.inline.hpp"
  80 #include "runtime/handles.inline.hpp"
  81 #include "runtime/javaCalls.hpp"
  82 #include "runtime/mutexLocker.hpp"
  83 #include "runtime/orderAccess.hpp"
  84 #include "runtime/reflectionUtils.hpp"
  85 #include "runtime/thread.inline.hpp"
  86 #include "services/classLoadingService.hpp"
  87 #include "services/threadService.hpp"
  88 #include "utilities/dtrace.hpp"
  89 #include "utilities/events.hpp"
  90 #include "utilities/macros.hpp"
  91 #include "utilities/stringUtils.hpp"
  92 #include "utilities/pair.hpp"
  93 #ifdef COMPILER1
  94 #include "c1/c1_Compiler.hpp"
  95 #endif
  96 #if INCLUDE_JFR
  97 #include "jfr/jfrEvents.hpp"
  98 #endif
  99 
 100 
 101 #ifdef DTRACE_ENABLED
 102 
 103 
 104 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
 105 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
 106 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
 107 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
 108 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
 109 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
 110 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
 111 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
 112 #define DTRACE_CLASSINIT_PROBE(type, thread_type)                \
 113   {                                                              \
 114     char* data = NULL;                                           \
 115     int len = 0;                                                 \
 116     Symbol* clss_name = name();                                  \
 117     if (clss_name != NULL) {                                     \
 118       data = (char*)clss_name->bytes();                          \
 119       len = clss_name->utf8_length();                            \
 120     }                                                            \
 121     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
 122       data, len, (void*)class_loader(), thread_type);            \
 123   }
 124 
 125 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)     \
 126   {                                                              \
 127     char* data = NULL;                                           \
 128     int len = 0;                                                 \
 129     Symbol* clss_name = name();                                  \
 130     if (clss_name != NULL) {                                     \
 131       data = (char*)clss_name->bytes();                          \
 132       len = clss_name->utf8_length();                            \
 133     }                                                            \
 134     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
 135       data, len, (void*)class_loader(), thread_type, wait);      \
 136   }
 137 
 138 #else //  ndef DTRACE_ENABLED
 139 
 140 #define DTRACE_CLASSINIT_PROBE(type, thread_type)
 141 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)
 142 
 143 #endif //  ndef DTRACE_ENABLED
 144 
 145 
 146 static inline bool is_class_loader(const Symbol* class_name,
 147                                    const ClassFileParser& parser) {
 148   assert(class_name != NULL, "invariant");
 149 
 150   if (class_name == vmSymbols::java_lang_ClassLoader()) {
 151     return true;
 152   }
 153 
 154   if (vmClasses::ClassLoader_klass_loaded()) {
 155     const Klass* const super_klass = parser.super_klass();
 156     if (super_klass != NULL) {
 157       if (super_klass->is_subtype_of(vmClasses::ClassLoader_klass())) {
 158         return true;
 159       }
 160     }
 161   }
 162   return false;
 163 }
 164 
 165 bool InstanceKlass::field_is_null_free_inline_type(int index) const { return Signature::basic_type(field(index)->signature(constants())) == T_INLINE_TYPE; }
 166 
 167 // private: called to verify that k is a static member of this nest.
 168 // We know that k is an instance class in the same package and hence the
 169 // same classloader.
 170 bool InstanceKlass::has_nest_member(JavaThread* current, InstanceKlass* k) const {
 171   assert(!is_hidden(), "unexpected hidden class");
 172   if (_nest_members == NULL || _nest_members == Universe::the_empty_short_array()) {
 173     if (log_is_enabled(Trace, class, nestmates)) {
 174       ResourceMark rm(current);
 175       log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
 176                                   k->external_name(), this->external_name());
 177     }
 178     return false;
 179   }
 180 
 181   if (log_is_enabled(Trace, class, nestmates)) {
 182     ResourceMark rm(current);
 183     log_trace(class, nestmates)("Checking nest membership of %s in %s",
 184                                 k->external_name(), this->external_name());
 185   }
 186 
 187   // Check for the named class in _nest_members.
 188   // We don't resolve, or load, any classes.
 189   for (int i = 0; i < _nest_members->length(); i++) {
 190     int cp_index = _nest_members->at(i);
 191     Symbol* name = _constants->klass_name_at(cp_index);
 192     if (name == k->name()) {
 193       log_trace(class, nestmates)("- named class found at nest_members[%d] => cp[%d]", i, cp_index);
 194       return true;
 195     }
 196   }
 197   log_trace(class, nestmates)("- class is NOT a nest member!");
 198   return false;
 199 }
 200 
 201 // Called to verify that k is a permitted subclass of this class
 202 bool InstanceKlass::has_as_permitted_subclass(const InstanceKlass* k) const {
 203   Thread* current = Thread::current();
 204   assert(k != NULL, "sanity check");
 205   assert(_permitted_subclasses != NULL && _permitted_subclasses != Universe::the_empty_short_array(),
 206          "unexpected empty _permitted_subclasses array");
 207 
 208   if (log_is_enabled(Trace, class, sealed)) {
 209     ResourceMark rm(current);
 210     log_trace(class, sealed)("Checking for permitted subclass of %s in %s",
 211                              k->external_name(), this->external_name());
 212   }
 213 
 214   // Check that the class and its super are in the same module.
 215   if (k->module() != this->module()) {
 216     ResourceMark rm(current);
 217     log_trace(class, sealed)("Check failed for same module of permitted subclass %s and sealed class %s",
 218                              k->external_name(), this->external_name());
 219     return false;
 220   }
 221 
 222   if (!k->is_public() && !is_same_class_package(k)) {
 223     ResourceMark rm(current);
 224     log_trace(class, sealed)("Check failed, subclass %s not public and not in the same package as sealed class %s",
 225                              k->external_name(), this->external_name());
 226     return false;
 227   }
 228 
 229   for (int i = 0; i < _permitted_subclasses->length(); i++) {
 230     int cp_index = _permitted_subclasses->at(i);
 231     Symbol* name = _constants->klass_name_at(cp_index);
 232     if (name == k->name()) {
 233       log_trace(class, sealed)("- Found it at permitted_subclasses[%d] => cp[%d]", i, cp_index);
 234       return true;
 235     }
 236   }
 237   log_trace(class, sealed)("- class is NOT a permitted subclass!");
 238   return false;
 239 }
 240 
 241 // Return nest-host class, resolving, validating and saving it if needed.
 242 // In cases where this is called from a thread that cannot do classloading
 243 // (such as a native JIT thread) then we simply return NULL, which in turn
 244 // causes the access check to return false. Such code will retry the access
 245 // from a more suitable environment later. Otherwise the _nest_host is always
 246 // set once this method returns.
 247 // Any errors from nest-host resolution must be preserved so they can be queried
 248 // from higher-level access checking code, and reported as part of access checking
 249 // exceptions.
 250 // VirtualMachineErrors are propagated with a NULL return.
 251 // Under any conditions where the _nest_host can be set to non-NULL the resulting
 252 // value of it and, if applicable, the nest host resolution/validation error,
 253 // are idempotent.
 254 InstanceKlass* InstanceKlass::nest_host(TRAPS) {
 255   InstanceKlass* nest_host_k = _nest_host;
 256   if (nest_host_k != NULL) {
 257     return nest_host_k;
 258   }
 259 
 260   ResourceMark rm(THREAD);
 261 
 262   // need to resolve and save our nest-host class.
 263   if (_nest_host_index != 0) { // we have a real nest_host
 264     // Before trying to resolve check if we're in a suitable context
 265     bool can_resolve = THREAD->can_call_java();
 266     if (!can_resolve && !_constants->tag_at(_nest_host_index).is_klass()) {
 267       log_trace(class, nestmates)("Rejected resolution of nest-host of %s in unsuitable thread",
 268                                   this->external_name());
 269       return NULL; // sentinel to say "try again from a different context"
 270     }
 271 
 272     log_trace(class, nestmates)("Resolving nest-host of %s using cp entry for %s",
 273                                 this->external_name(),
 274                                 _constants->klass_name_at(_nest_host_index)->as_C_string());
 275 
 276     Klass* k = _constants->klass_at(_nest_host_index, THREAD);
 277     if (HAS_PENDING_EXCEPTION) {
 278       if (PENDING_EXCEPTION->is_a(vmClasses::VirtualMachineError_klass())) {
 279         return NULL; // propagate VMEs
 280       }
 281       stringStream ss;
 282       char* target_host_class = _constants->klass_name_at(_nest_host_index)->as_C_string();
 283       ss.print("Nest host resolution of %s with host %s failed: ",
 284                this->external_name(), target_host_class);
 285       java_lang_Throwable::print(PENDING_EXCEPTION, &ss);
 286       const char* msg = ss.as_string(true /* on C-heap */);
 287       constantPoolHandle cph(THREAD, constants());
 288       SystemDictionary::add_nest_host_error(cph, _nest_host_index, msg);
 289       CLEAR_PENDING_EXCEPTION;
 290 
 291       log_trace(class, nestmates)("%s", msg);
 292     } else {
 293       // A valid nest-host is an instance class in the current package that lists this
 294       // class as a nest member. If any of these conditions are not met the class is
 295       // its own nest-host.
 296       const char* error = NULL;
 297 
 298       // JVMS 5.4.4 indicates package check comes first
 299       if (is_same_class_package(k)) {
 300         // Now check actual membership. We can't be a member if our "host" is
 301         // not an instance class.
 302         if (k->is_instance_klass()) {
 303           nest_host_k = InstanceKlass::cast(k);
 304           bool is_member = nest_host_k->has_nest_member(THREAD, this);
 305           if (is_member) {
 306             _nest_host = nest_host_k; // save resolved nest-host value
 307 
 308             log_trace(class, nestmates)("Resolved nest-host of %s to %s",
 309                                         this->external_name(), k->external_name());
 310             return nest_host_k;
 311           } else {
 312             error = "current type is not listed as a nest member";
 313           }
 314         } else {
 315           error = "host is not an instance class";
 316         }
 317       } else {
 318         error = "types are in different packages";
 319       }
 320 
 321       // something went wrong, so record what and log it
 322       {
 323         stringStream ss;
 324         ss.print("Type %s (loader: %s) is not a nest member of type %s (loader: %s): %s",
 325                  this->external_name(),
 326                  this->class_loader_data()->loader_name_and_id(),
 327                  k->external_name(),
 328                  k->class_loader_data()->loader_name_and_id(),
 329                  error);
 330         const char* msg = ss.as_string(true /* on C-heap */);
 331         constantPoolHandle cph(THREAD, constants());
 332         SystemDictionary::add_nest_host_error(cph, _nest_host_index, msg);
 333         log_trace(class, nestmates)("%s", msg);
 334       }
 335     }
 336   } else {
 337     log_trace(class, nestmates)("Type %s is not part of a nest: setting nest-host to self",
 338                                 this->external_name());
 339   }
 340 
 341   // Either not in an explicit nest, or else an error occurred, so
 342   // the nest-host is set to `this`. Any thread that sees this assignment
 343   // will also see any setting of nest_host_error(), if applicable.
 344   return (_nest_host = this);
 345 }
 346 
 347 // Dynamic nest member support: set this class's nest host to the given class.
 348 // This occurs as part of the class definition, as soon as the instanceKlass
 349 // has been created and doesn't require further resolution. The code:
 350 //    lookup().defineHiddenClass(bytes_for_X, NESTMATE);
 351 // results in:
 352 //    class_of_X.set_nest_host(lookup().lookupClass().getNestHost())
 353 // If it has an explicit _nest_host_index or _nest_members, these will be ignored.
 354 // We also know the "host" is a valid nest-host in the same package so we can
 355 // assert some of those facts.
 356 void InstanceKlass::set_nest_host(InstanceKlass* host) {
 357   assert(is_hidden(), "must be a hidden class");
 358   assert(host != NULL, "NULL nest host specified");
 359   assert(_nest_host == NULL, "current class has resolved nest-host");
 360   assert(nest_host_error() == NULL, "unexpected nest host resolution error exists: %s",
 361          nest_host_error());
 362   assert((host->_nest_host == NULL && host->_nest_host_index == 0) ||
 363          (host->_nest_host == host), "proposed host is not a valid nest-host");
 364   // Can't assert this as package is not set yet:
 365   // assert(is_same_class_package(host), "proposed host is in wrong package");
 366 
 367   if (log_is_enabled(Trace, class, nestmates)) {
 368     ResourceMark rm;
 369     const char* msg = "";
 370     // a hidden class does not expect a statically defined nest-host
 371     if (_nest_host_index > 0) {
 372       msg = "(the NestHost attribute in the current class is ignored)";
 373     } else if (_nest_members != NULL && _nest_members != Universe::the_empty_short_array()) {
 374       msg = "(the NestMembers attribute in the current class is ignored)";
 375     }
 376     log_trace(class, nestmates)("Injected type %s into the nest of %s %s",
 377                                 this->external_name(),
 378                                 host->external_name(),
 379                                 msg);
 380   }
 381   // set dynamic nest host
 382   _nest_host = host;
 383   // Record dependency to keep nest host from being unloaded before this class.
 384   ClassLoaderData* this_key = class_loader_data();
 385   this_key->record_dependency(host);
 386 }
 387 
 388 // check if 'this' and k are nestmates (same nest_host), or k is our nest_host,
 389 // or we are k's nest_host - all of which is covered by comparing the two
 390 // resolved_nest_hosts.
 391 // Any exceptions (i.e. VMEs) are propagated.
 392 bool InstanceKlass::has_nestmate_access_to(InstanceKlass* k, TRAPS) {
 393 
 394   assert(this != k, "this should be handled by higher-level code");
 395 
 396   // Per JVMS 5.4.4 we first resolve and validate the current class, then
 397   // the target class k.
 398 
 399   InstanceKlass* cur_host = nest_host(CHECK_false);
 400   if (cur_host == NULL) {
 401     return false;
 402   }
 403 
 404   Klass* k_nest_host = k->nest_host(CHECK_false);
 405   if (k_nest_host == NULL) {
 406     return false;
 407   }
 408 
 409   bool access = (cur_host == k_nest_host);
 410 
 411   ResourceMark rm(THREAD);
 412   log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
 413                               this->external_name(),
 414                               access ? "" : "NOT ",
 415                               k->external_name());
 416   return access;
 417 }
 418 
 419 const char* InstanceKlass::nest_host_error() {
 420   if (_nest_host_index == 0) {
 421     return NULL;
 422   } else {
 423     constantPoolHandle cph(Thread::current(), constants());
 424     return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index);
 425   }
 426 }
 427 
 428 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
 429   const int size = InstanceKlass::size(parser.vtable_size(),
 430                                        parser.itable_size(),
 431                                        nonstatic_oop_map_size(parser.total_oop_map_count()),
 432                                        parser.is_interface(),
 433                                        parser.has_inline_fields() ? parser.java_fields_count() : 0,
 434                                        parser.is_inline_type());
 435 
 436   const Symbol* const class_name = parser.class_name();
 437   assert(class_name != NULL, "invariant");
 438   ClassLoaderData* loader_data = parser.loader_data();
 439   assert(loader_data != NULL, "invariant");
 440 
 441   InstanceKlass* ik;
 442 
 443   // Allocation
 444   if (REF_NONE == parser.reference_type()) {
 445     if (class_name == vmSymbols::java_lang_Class()) {
 446       // mirror
 447       ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
 448     } else if (is_class_loader(class_name, parser)) {

 449       // class loader
 450       ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);
 451     } else if (parser.is_inline_type()) {
 452       // inline type
 453       ik = new (loader_data, size, THREAD) InlineKlass(parser);
 454     } else {
 455       // normal
 456       ik = new (loader_data, size, THREAD) InstanceKlass(parser, InstanceKlass::_kind_other);
 457     }
 458   } else {
 459     // reference
 460     ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
 461   }
 462 
 463   // Check for pending exception before adding to the loader data and incrementing
 464   // class count.  Can get OOM here.
 465   if (HAS_PENDING_EXCEPTION) {
 466     return NULL;
 467   }
 468 
 469 #ifdef ASSERT
 470   assert(ik->size() == size, "");
 471   ik->bounds_check((address) ik->start_of_vtable(), false, size);
 472   ik->bounds_check((address) ik->start_of_itable(), false, size);
 473   ik->bounds_check((address) ik->end_of_itable(), true, size);
 474   ik->bounds_check((address) ik->end_of_nonstatic_oop_maps(), true, size);
 475 #endif //ASSERT
 476   return ik;
 477 }
 478 
 479 #ifndef PRODUCT
 480 bool InstanceKlass::bounds_check(address addr, bool edge_ok, intptr_t size_in_bytes) const {
 481   const char* bad = NULL;
 482   address end = NULL;
 483   if (addr < (address)this) {
 484     bad = "before";
 485   } else if (addr == (address)this) {
 486     if (edge_ok)  return true;
 487     bad = "just before";
 488   } else if (addr == (end = (address)this + sizeof(intptr_t) * (size_in_bytes < 0 ? size() : size_in_bytes))) {
 489     if (edge_ok)  return true;
 490     bad = "just after";
 491   } else if (addr > end) {
 492     bad = "after";
 493   } else {
 494     return true;
 495   }
 496   tty->print_cr("%s object bounds: " INTPTR_FORMAT " [" INTPTR_FORMAT ".." INTPTR_FORMAT "]",
 497       bad, (intptr_t)addr, (intptr_t)this, (intptr_t)end);
 498   Verbose = WizardMode = true; this->print(); //@@
 499   return false;
 500 }
 501 #endif //PRODUCT
 502 
 503 // copy method ordering from resource area to Metaspace
 504 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
 505   if (m != NULL) {
 506     // allocate a new array and copy contents (memcpy?)
 507     _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
 508     for (int i = 0; i < m->length(); i++) {
 509       _method_ordering->at_put(i, m->at(i));
 510     }
 511   } else {
 512     _method_ordering = Universe::the_empty_int_array();
 513   }
 514 }
 515 
 516 // create a new array of vtable_indices for default methods
 517 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
 518   Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
 519   assert(default_vtable_indices() == NULL, "only create once");
 520   set_default_vtable_indices(vtable_indices);
 521   return vtable_indices;
 522 }
 523 
 524 InstanceKlass::InstanceKlass(const ClassFileParser& parser, unsigned kind, KlassID id) :
 525   Klass(id),
 526   _nest_members(NULL),
 527   _nest_host(NULL),
 528   _permitted_subclasses(NULL),
 529   _record_components(NULL),
 530   _static_field_size(parser.static_field_size()),
 531   _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
 532   _itable_len(parser.itable_size()),
 533   _nest_host_index(0),
 534   _init_state(allocated),
 535   _reference_type(parser.reference_type()),
 536   _init_thread(NULL),
 537   _inline_type_field_klasses(NULL),
 538   _adr_inlineklass_fixed_block(NULL)
 539 {
 540   set_vtable_length(parser.vtable_size());
 541   set_kind(kind);
 542   set_access_flags(parser.access_flags());
 543   if (parser.is_hidden()) set_is_hidden();
 544   set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
 545                                                     false));
 546     if (parser.has_inline_fields()) {
 547       set_has_inline_type_fields();
 548     }
 549     _java_fields_count = parser.java_fields_count();
 550 
 551   assert(NULL == _methods, "underlying memory not zeroed?");
 552   assert(is_instance_klass(), "is layout incorrect?");
 553   assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
 554 
 555   if (has_inline_type_fields()) {
 556     _inline_type_field_klasses = (const Klass**) adr_inline_type_field_klasses();
 557   }
 558 }
 559 
 560 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
 561                                        Array<Method*>* methods) {
 562   if (methods != NULL && methods != Universe::the_empty_method_array() &&
 563       !methods->is_shared()) {
 564     for (int i = 0; i < methods->length(); i++) {
 565       Method* method = methods->at(i);
 566       if (method == NULL) continue;  // maybe null if error processing
 567       // Only want to delete methods that are not executing for RedefineClasses.
 568       // The previous version will point to them so they're not totally dangling
 569       assert (!method->on_stack(), "shouldn't be called with methods on stack");
 570       MetadataFactory::free_metadata(loader_data, method);
 571     }
 572     MetadataFactory::free_array<Method*>(loader_data, methods);
 573   }
 574 }
 575 
 576 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
 577                                           const Klass* super_klass,
 578                                           Array<InstanceKlass*>* local_interfaces,
 579                                           Array<InstanceKlass*>* transitive_interfaces) {
 580   // Only deallocate transitive interfaces if not empty, same as super class
 581   // or same as local interfaces.  See code in parseClassFile.
 582   Array<InstanceKlass*>* ti = transitive_interfaces;
 583   if (ti != Universe::the_empty_instance_klass_array() && ti != local_interfaces) {
 584     // check that the interfaces don't come from super class
 585     Array<InstanceKlass*>* sti = (super_klass == NULL) ? NULL :
 586                     InstanceKlass::cast(super_klass)->transitive_interfaces();
 587     if (ti != sti && ti != NULL && !ti->is_shared() &&
 588         ti != Universe::the_single_IdentityObject_klass_array() &&
 589         ti != Universe::the_single_PrimitiveObject_klass_array()) {
 590       MetadataFactory::free_array<InstanceKlass*>(loader_data, ti);
 591     }
 592   }
 593 
 594   // local interfaces can be empty
 595   if (local_interfaces != Universe::the_empty_instance_klass_array() &&
 596       local_interfaces != NULL && !local_interfaces->is_shared() &&
 597       local_interfaces != Universe::the_single_IdentityObject_klass_array() &&
 598       local_interfaces != Universe::the_single_PrimitiveObject_klass_array()) {
 599     MetadataFactory::free_array<InstanceKlass*>(loader_data, local_interfaces);
 600   }
 601 }
 602 
 603 void InstanceKlass::deallocate_record_components(ClassLoaderData* loader_data,
 604                                                  Array<RecordComponent*>* record_components) {
 605   if (record_components != NULL && !record_components->is_shared()) {
 606     for (int i = 0; i < record_components->length(); i++) {
 607       RecordComponent* record_component = record_components->at(i);
 608       MetadataFactory::free_metadata(loader_data, record_component);
 609     }
 610     MetadataFactory::free_array<RecordComponent*>(loader_data, record_components);
 611   }
 612 }
 613 
 614 // This function deallocates the metadata and C heap pointers that the
 615 // InstanceKlass points to.
 616 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
 617 
 618   // Orphan the mirror first, CMS thinks it's still live.
 619   if (java_mirror() != NULL) {
 620     java_lang_Class::set_klass(java_mirror(), NULL);
 621   }
 622 
 623   // Also remove mirror from handles
 624   loader_data->remove_handle(_java_mirror);
 625 
 626   // Need to take this class off the class loader data list.
 627   loader_data->remove_class(this);
 628 
 629   // The array_klass for this class is created later, after error handling.
 630   // For class redefinition, we keep the original class so this scratch class
 631   // doesn't have an array class.  Either way, assert that there is nothing
 632   // to deallocate.
 633   assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
 634 
 635   // Release C heap allocated data that this points to, which includes
 636   // reference counting symbol names.
 637   release_C_heap_structures_internal();
 638 
 639   deallocate_methods(loader_data, methods());
 640   set_methods(NULL);
 641 
 642   deallocate_record_components(loader_data, record_components());
 643   set_record_components(NULL);
 644 
 645   if (method_ordering() != NULL &&
 646       method_ordering() != Universe::the_empty_int_array() &&
 647       !method_ordering()->is_shared()) {
 648     MetadataFactory::free_array<int>(loader_data, method_ordering());
 649   }
 650   set_method_ordering(NULL);
 651 
 652   // default methods can be empty
 653   if (default_methods() != NULL &&
 654       default_methods() != Universe::the_empty_method_array() &&
 655       !default_methods()->is_shared()) {
 656     MetadataFactory::free_array<Method*>(loader_data, default_methods());
 657   }
 658   // Do NOT deallocate the default methods, they are owned by superinterfaces.
 659   set_default_methods(NULL);
 660 
 661   // default methods vtable indices can be empty
 662   if (default_vtable_indices() != NULL &&
 663       !default_vtable_indices()->is_shared()) {
 664     MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
 665   }
 666   set_default_vtable_indices(NULL);
 667 
 668 
 669   // This array is in Klass, but remove it with the InstanceKlass since
 670   // this place would be the only caller and it can share memory with transitive
 671   // interfaces.
 672   if (secondary_supers() != NULL &&
 673       secondary_supers() != Universe::the_empty_klass_array() &&
 674       // see comments in compute_secondary_supers about the following cast
 675       (address)(secondary_supers()) != (address)(transitive_interfaces()) &&
 676       !secondary_supers()->is_shared()) {
 677     MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
 678   }
 679   set_secondary_supers(NULL);
 680 
 681   deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
 682   set_transitive_interfaces(NULL);
 683   set_local_interfaces(NULL);
 684 
 685   if (fields() != NULL && !fields()->is_shared()) {
 686     MetadataFactory::free_array<jushort>(loader_data, fields());
 687   }
 688   set_fields(NULL, 0);
 689 
 690   // If a method from a redefined class is using this constant pool, don't
 691   // delete it, yet.  The new class's previous version will point to this.
 692   if (constants() != NULL) {
 693     assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
 694     if (!constants()->is_shared()) {
 695       MetadataFactory::free_metadata(loader_data, constants());
 696     }
 697     // Delete any cached resolution errors for the constant pool
 698     SystemDictionary::delete_resolution_error(constants());
 699 
 700     set_constants(NULL);
 701   }
 702 
 703   if (inner_classes() != NULL &&
 704       inner_classes() != Universe::the_empty_short_array() &&
 705       !inner_classes()->is_shared()) {
 706     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
 707   }
 708   set_inner_classes(NULL);
 709 
 710   if (nest_members() != NULL &&
 711       nest_members() != Universe::the_empty_short_array() &&
 712       !nest_members()->is_shared()) {
 713     MetadataFactory::free_array<jushort>(loader_data, nest_members());
 714   }
 715   set_nest_members(NULL);
 716 
 717   if (permitted_subclasses() != NULL &&
 718       permitted_subclasses() != Universe::the_empty_short_array() &&
 719       !permitted_subclasses()->is_shared()) {
 720     MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
 721   }
 722   set_permitted_subclasses(NULL);
 723 
 724   // We should deallocate the Annotations instance if it's not in shared spaces.
 725   if (annotations() != NULL && !annotations()->is_shared()) {
 726     MetadataFactory::free_metadata(loader_data, annotations());
 727   }
 728   set_annotations(NULL);
 729 
 730   SystemDictionaryShared::handle_class_unloading(this);
 731 }
 732 
 733 bool InstanceKlass::is_record() const {
 734   return _record_components != NULL &&
 735          is_final() &&
 736          java_super() == vmClasses::Record_klass();
 737 }
 738 
 739 bool InstanceKlass::is_sealed() const {
 740   return _permitted_subclasses != NULL &&
 741          _permitted_subclasses != Universe::the_empty_short_array();
 742 }
 743 
 744 bool InstanceKlass::should_be_initialized() const {
 745   return !is_initialized();
 746 }
 747 
 748 klassItable InstanceKlass::itable() const {
 749   return klassItable(const_cast<InstanceKlass*>(this));
 750 }
 751 
 752 void InstanceKlass::eager_initialize(Thread *thread) {
 753   if (!EagerInitialization) return;
 754 
 755   if (this->is_not_initialized()) {
 756     // abort if the the class has a class initializer
 757     if (this->class_initializer() != NULL) return;
 758 
 759     // abort if it is java.lang.Object (initialization is handled in genesis)
 760     Klass* super_klass = super();
 761     if (super_klass == NULL) return;
 762 
 763     // abort if the super class should be initialized
 764     if (!InstanceKlass::cast(super_klass)->is_initialized()) return;
 765 
 766     // call body to expose the this pointer
 767     eager_initialize_impl();
 768   }
 769 }
 770 
 771 // JVMTI spec thinks there are signers and protection domain in the
 772 // instanceKlass.  These accessors pretend these fields are there.
 773 // The hprof specification also thinks these fields are in InstanceKlass.
 774 oop InstanceKlass::protection_domain() const {
 775   // return the protection_domain from the mirror
 776   return java_lang_Class::protection_domain(java_mirror());
 777 }
 778 
 779 // To remove these from requires an incompatible change and CCC request.
 780 objArrayOop InstanceKlass::signers() const {
 781   // return the signers from the mirror
 782   return java_lang_Class::signers(java_mirror());
 783 }
 784 
 785 oop InstanceKlass::init_lock() const {
 786   // return the init lock from the mirror
 787   oop lock = java_lang_Class::init_lock(java_mirror());
 788   // Prevent reordering with any access of initialization state
 789   OrderAccess::loadload();
 790   assert(lock != NULL || !is_not_initialized(), // initialized or in_error state
 791          "only fully initialized state can have a null lock");
 792   return lock;
 793 }
 794 
 795 // Set the initialization lock to null so the object can be GC'ed.  Any racing
 796 // threads to get this lock will see a null lock and will not lock.
 797 // That's okay because they all check for initialized state after getting
 798 // the lock and return.
 799 void InstanceKlass::fence_and_clear_init_lock() {
 800   // make sure previous stores are all done, notably the init_state.
 801   OrderAccess::storestore();
 802   java_lang_Class::clear_init_lock(java_mirror());
 803   assert(!is_not_initialized(), "class must be initialized now");
 804 }
 805 
 806 void InstanceKlass::eager_initialize_impl() {
 807   EXCEPTION_MARK;
 808   HandleMark hm(THREAD);
 809   Handle h_init_lock(THREAD, init_lock());
 810   ObjectLocker ol(h_init_lock, THREAD);
 811 
 812   // abort if someone beat us to the initialization
 813   if (!is_not_initialized()) return;  // note: not equivalent to is_initialized()
 814 
 815   ClassState old_state = init_state();
 816   link_class_impl(THREAD);
 817   if (HAS_PENDING_EXCEPTION) {
 818     CLEAR_PENDING_EXCEPTION;
 819     // Abort if linking the class throws an exception.
 820 
 821     // Use a test to avoid redundantly resetting the state if there's
 822     // no change.  Set_init_state() asserts that state changes make
 823     // progress, whereas here we might just be spinning in place.
 824     if (old_state != _init_state)
 825       set_init_state(old_state);
 826   } else {
 827     // linking successfull, mark class as initialized
 828     set_init_state(fully_initialized);
 829     fence_and_clear_init_lock();
 830     // trace
 831     if (log_is_enabled(Info, class, init)) {
 832       ResourceMark rm(THREAD);
 833       log_info(class, init)("[Initialized %s without side effects]", external_name());
 834     }
 835   }
 836 }
 837 
 838 
 839 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
 840 // process. The step comments refers to the procedure described in that section.
 841 // Note: implementation moved to static method to expose the this pointer.
 842 void InstanceKlass::initialize(TRAPS) {
 843   if (this->should_be_initialized()) {
 844     initialize_impl(CHECK);
 845     // Note: at this point the class may be initialized
 846     //       OR it may be in the state of being initialized
 847     //       in case of recursive initialization!
 848   } else {
 849     assert(is_initialized(), "sanity check");
 850   }
 851 }
 852 
 853 
 854 bool InstanceKlass::verify_code(TRAPS) {
 855   // 1) Verify the bytecodes
 856   return Verifier::verify(this, should_verify_class(), THREAD);
 857 }
 858 
 859 void InstanceKlass::link_class(TRAPS) {
 860   assert(is_loaded(), "must be loaded");
 861   if (!is_linked()) {
 862     link_class_impl(CHECK);
 863   }
 864 }
 865 
 866 // Called to verify that a class can link during initialization, without
 867 // throwing a VerifyError.
 868 bool InstanceKlass::link_class_or_fail(TRAPS) {
 869   assert(is_loaded(), "must be loaded");
 870   if (!is_linked()) {
 871     link_class_impl(CHECK_false);
 872   }
 873   return is_linked();
 874 }
 875 
 876 bool InstanceKlass::link_class_impl(TRAPS) {
 877   if (DumpSharedSpaces && SystemDictionaryShared::has_class_failed_verification(this)) {
 878     // This is for CDS dumping phase only -- we use the in_error_state to indicate that
 879     // the class has failed verification. Throwing the NoClassDefFoundError here is just
 880     // a convenient way to stop repeat attempts to verify the same (bad) class.
 881     //
 882     // Note that the NoClassDefFoundError is not part of the JLS, and should not be thrown
 883     // if we are executing Java code. This is not a problem for CDS dumping phase since
 884     // it doesn't execute any Java code.
 885     ResourceMark rm(THREAD);
 886     Exceptions::fthrow(THREAD_AND_LOCATION,
 887                        vmSymbols::java_lang_NoClassDefFoundError(),
 888                        "Class %s, or one of its supertypes, failed class initialization",
 889                        external_name());
 890     return false;
 891   }
 892   // return if already verified
 893   if (is_linked()) {
 894     return true;
 895   }
 896 
 897   // Timing
 898   // timer handles recursion
 899   JavaThread* jt = THREAD;
 900 
 901   // link super class before linking this class
 902   Klass* super_klass = super();
 903   if (super_klass != NULL) {
 904     if (super_klass->is_interface()) {  // check if super class is an interface
 905       ResourceMark rm(THREAD);
 906       Exceptions::fthrow(
 907         THREAD_AND_LOCATION,
 908         vmSymbols::java_lang_IncompatibleClassChangeError(),
 909         "class %s has interface %s as super class",
 910         external_name(),
 911         super_klass->external_name()
 912       );
 913       return false;
 914     }
 915 
 916     InstanceKlass* ik_super = InstanceKlass::cast(super_klass);
 917     ik_super->link_class_impl(CHECK_false);
 918   }
 919 
 920   // link all interfaces implemented by this class before linking this class
 921   Array<InstanceKlass*>* interfaces = local_interfaces();
 922   int num_interfaces = interfaces->length();
 923   for (int index = 0; index < num_interfaces; index++) {
 924     InstanceKlass* interk = interfaces->at(index);
 925     interk->link_class_impl(CHECK_false);
 926   }
 927 
 928 
 929   // If a class declares a method that uses an inline class as an argument
 930   // type or return inline type, this inline class must be loaded during the
 931   // linking of this class because size and properties of the inline class
 932   // must be known in order to be able to perform inline type optimizations.
 933   // The implementation below is an approximation of this rule, the code
 934   // iterates over all methods of the current class (including overridden
 935   // methods), not only the methods declared by this class. This
 936   // approximation makes the code simpler, and doesn't change the semantic
 937   // because classes declaring methods overridden by the current class are
 938   // linked (and have performed their own pre-loading) before the linking
 939   // of the current class.
 940 
 941 
 942   // Note:
 943   // Inline class types are loaded during
 944   // the loading phase (see ClassFileParser::post_process_parsed_stream()).
 945   // Inline class types used as element types for array creation
 946   // are not pre-loaded. Their loading is triggered by either anewarray
 947   // or multianewarray bytecodes.
 948 
 949   // Could it be possible to do the following processing only if the
 950   // class uses inline types?
 951   if (EnableValhalla) {
 952     ResourceMark rm(THREAD);
 953     for (int i = 0; i < methods()->length(); i++) {
 954       Method* m = methods()->at(i);
 955       for (SignatureStream ss(m->signature()); !ss.is_done(); ss.next()) {
 956         if (ss.is_reference()) {
 957           if (ss.is_array()) {
 958             continue;
 959           }
 960           if (ss.type() == T_INLINE_TYPE) {
 961             Symbol* symb = ss.as_symbol();
 962 
 963             oop loader = class_loader();
 964             oop protection_domain = this->protection_domain();
 965             Klass* klass = SystemDictionary::resolve_or_fail(symb,
 966                                                              Handle(THREAD, loader), Handle(THREAD, protection_domain), true,
 967                                                              CHECK_false);
 968             if (klass == NULL) {
 969               THROW_(vmSymbols::java_lang_LinkageError(), false);
 970             }
 971             if (!klass->is_inline_klass()) {
 972               Exceptions::fthrow(
 973                 THREAD_AND_LOCATION,
 974                 vmSymbols::java_lang_IncompatibleClassChangeError(),
 975                 "class %s is not an inline type",
 976                 klass->external_name());
 977             }
 978           }
 979         }
 980       }
 981     }
 982   }
 983 
 984   // in case the class is linked in the process of linking its superclasses
 985   if (is_linked()) {
 986     return true;
 987   }
 988 
 989   // trace only the link time for this klass that includes
 990   // the verification time
 991   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
 992                              ClassLoader::perf_class_link_selftime(),
 993                              ClassLoader::perf_classes_linked(),
 994                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 995                              jt->get_thread_stat()->perf_timers_addr(),
 996                              PerfClassTraceTime::CLASS_LINK);
 997 
 998   // verification & rewriting
 999   {
1000     HandleMark hm(THREAD);
1001     Handle h_init_lock(THREAD, init_lock());
1002     ObjectLocker ol(h_init_lock, jt);
1003     // rewritten will have been set if loader constraint error found
1004     // on an earlier link attempt
1005     // don't verify or rewrite if already rewritten
1006     //
1007 
1008     if (!is_linked()) {
1009       if (!is_rewritten()) {
1010         if (is_shared()) {
1011           assert(!verified_at_dump_time(), "must be");
1012         }
1013         {
1014           bool verify_ok = verify_code(THREAD);
1015           if (!verify_ok) {
1016             return false;
1017           }
1018         }
1019 
1020         // Just in case a side-effect of verify linked this class already
1021         // (which can sometimes happen since the verifier loads classes
1022         // using custom class loaders, which are free to initialize things)
1023         if (is_linked()) {
1024           return true;
1025         }
1026 
1027         // also sets rewritten
1028         rewrite_class(CHECK_false);
1029       } else if (is_shared()) {
1030         SystemDictionaryShared::check_verification_constraints(this, CHECK_false);
1031       }
1032 
1033       // relocate jsrs and link methods after they are all rewritten
1034       link_methods(CHECK_false);
1035 
1036       // Initialize the vtable and interface table after
1037       // methods have been rewritten since rewrite may
1038       // fabricate new Method*s.
1039       // also does loader constraint checking
1040       //
1041       // initialize_vtable and initialize_itable need to be rerun
1042       // for a shared class if
1043       // 1) the class is loaded by custom class loader or
1044       // 2) the class is loaded by built-in class loader but failed to add archived loader constraints or
1045       // 3) the class was not verified during dump time
1046       bool need_init_table = true;
1047       if (is_shared() && verified_at_dump_time() &&
1048           SystemDictionaryShared::check_linking_constraints(THREAD, this)) {
1049         need_init_table = false;
1050       }
1051       if (need_init_table) {
1052         vtable().initialize_vtable_and_check_constraints(CHECK_false);
1053         itable().initialize_itable_and_check_constraints(CHECK_false);
1054       }
1055 #ifdef ASSERT
1056       vtable().verify(tty, true);
1057       // In case itable verification is ever added.
1058       // itable().verify(tty, true);
1059 #endif
1060       if (UseVtableBasedCHA) {
1061         MutexLocker ml(THREAD, Compile_lock);
1062         set_init_state(linked);
1063 
1064         // Now flush all code that assume the class is not linked.
1065         if (Universe::is_fully_initialized()) {
1066           CodeCache::flush_dependents_on(this);
1067         }
1068       } else {
1069         set_init_state(linked);
1070       }
1071       if (JvmtiExport::should_post_class_prepare()) {
1072         JvmtiExport::post_class_prepare(THREAD, this);
1073       }
1074     }
1075   }
1076   return true;
1077 }
1078 
1079 // Rewrite the byte codes of all of the methods of a class.
1080 // The rewriter must be called exactly once. Rewriting must happen after
1081 // verification but before the first method of the class is executed.
1082 void InstanceKlass::rewrite_class(TRAPS) {
1083   assert(is_loaded(), "must be loaded");
1084   if (is_rewritten()) {
1085     assert(is_shared(), "rewriting an unshared class?");
1086     return;
1087   }
1088   Rewriter::rewrite(this, CHECK);
1089   set_rewritten();
1090 }
1091 
1092 // Now relocate and link method entry points after class is rewritten.
1093 // This is outside is_rewritten flag. In case of an exception, it can be
1094 // executed more than once.
1095 void InstanceKlass::link_methods(TRAPS) {
1096   int len = methods()->length();
1097   for (int i = len-1; i >= 0; i--) {
1098     methodHandle m(THREAD, methods()->at(i));
1099 
1100     // Set up method entry points for compiler and interpreter    .
1101     m->link_method(m, CHECK);
1102   }
1103 }
1104 
1105 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
1106 void InstanceKlass::initialize_super_interfaces(TRAPS) {
1107   assert (has_nonstatic_concrete_methods(), "caller should have checked this");
1108   for (int i = 0; i < local_interfaces()->length(); ++i) {
1109     InstanceKlass* ik = local_interfaces()->at(i);
1110 
1111     // Initialization is depth first search ie. we start with top of the inheritance tree
1112     // has_nonstatic_concrete_methods drives searching superinterfaces since it
1113     // means has_nonstatic_concrete_methods in its superinterface hierarchy
1114     if (ik->has_nonstatic_concrete_methods()) {
1115       ik->initialize_super_interfaces(CHECK);
1116     }
1117 
1118     // Only initialize() interfaces that "declare" concrete methods.
1119     if (ik->should_be_initialized() && ik->declares_nonstatic_concrete_methods()) {
1120       ik->initialize(CHECK);
1121     }
1122   }
1123 }
1124 
1125 ResourceHashtable<const InstanceKlass*, OopHandle, 107, ResourceObj::C_HEAP, mtClass>
1126       _initialization_error_table;
1127 
1128 void InstanceKlass::add_initialization_error(JavaThread* current, Handle exception) {
1129   // Create the same exception with a message indicating the thread name,
1130   // and the StackTraceElements.
1131   // If the initialization error is OOM, this might not work, but if GC kicks in
1132   // this would be still be helpful.
1133   JavaThread* THREAD = current;
1134   Handle cause = java_lang_Throwable::get_cause_with_stack_trace(exception, THREAD);
1135   if (HAS_PENDING_EXCEPTION || cause.is_null()) {
1136     CLEAR_PENDING_EXCEPTION;
1137     return;
1138   }
1139 
1140   MutexLocker ml(THREAD, ClassInitError_lock);
1141   OopHandle elem = OopHandle(Universe::vm_global(), cause());
1142   bool created = false;
1143   _initialization_error_table.put_if_absent(this, elem, &created);
1144   assert(created, "Initialization is single threaded");
1145   ResourceMark rm(THREAD);
1146   log_trace(class, init)("Initialization error added for class %s", external_name());
1147 }
1148 
1149 oop InstanceKlass::get_initialization_error(JavaThread* current) {
1150   MutexLocker ml(current, ClassInitError_lock);
1151   OopHandle* h = _initialization_error_table.get(this);
1152   return (h != nullptr) ? h->resolve() : nullptr;
1153 }
1154 
1155 // Need to remove entries for unloaded classes.
1156 void InstanceKlass::clean_initialization_error_table() {
1157   struct InitErrorTableCleaner {
1158     bool do_entry(const InstanceKlass* ik, OopHandle h) {
1159       if (!ik->is_loader_alive()) {
1160         h.release(Universe::vm_global());
1161         return true;
1162       } else {
1163         return false;
1164       }
1165     }
1166   };
1167 
1168   MutexLocker ml(ClassInitError_lock);
1169   InitErrorTableCleaner cleaner;
1170   _initialization_error_table.unlink(&cleaner);
1171 }
1172 
1173 void InstanceKlass::initialize_impl(TRAPS) {
1174   HandleMark hm(THREAD);
1175 
1176   // Make sure klass is linked (verified) before initialization
1177   // A class could already be verified, since it has been reflected upon.
1178   link_class(CHECK);
1179 
1180   DTRACE_CLASSINIT_PROBE(required, -1);
1181 
1182   bool wait = false;
1183 
1184   JavaThread* jt = THREAD;
1185 
1186   // refer to the JVM book page 47 for description of steps
1187   // Step 1
1188   {
1189     Handle h_init_lock(THREAD, init_lock());
1190     ObjectLocker ol(h_init_lock, jt);
1191 
1192     // Step 2
1193     // If we were to use wait() instead of waitInterruptibly() then
1194     // we might end up throwing IE from link/symbol resolution sites
1195     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
1196     while (is_being_initialized() && !is_reentrant_initialization(jt)) {
1197       wait = true;
1198       jt->set_class_to_be_initialized(this);
1199       ol.wait_uninterruptibly(jt);
1200       jt->set_class_to_be_initialized(NULL);
1201     }
1202 
1203     // Step 3
1204     if (is_being_initialized() && is_reentrant_initialization(jt)) {
1205       DTRACE_CLASSINIT_PROBE_WAIT(recursive, -1, wait);
1206       return;
1207     }
1208 
1209     // Step 4
1210     if (is_initialized()) {
1211       DTRACE_CLASSINIT_PROBE_WAIT(concurrent, -1, wait);
1212       return;
1213     }
1214 
1215     // Step 5
1216     if (is_in_error_state()) {
1217       DTRACE_CLASSINIT_PROBE_WAIT(erroneous, -1, wait);
1218       ResourceMark rm(THREAD);
1219       Handle cause(THREAD, get_initialization_error(THREAD));
1220 
1221       stringStream ss;
1222       ss.print("Could not initialize class %s", external_name());
1223       if (cause.is_null()) {
1224         THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), ss.as_string());
1225       } else {
1226         THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1227                         ss.as_string(), cause);
1228       }
1229     }
1230 
1231     // Step 6
1232     set_init_state(being_initialized);
1233     set_init_thread(jt);
1234   }
1235 
1236   // Pre-allocating an instance of the default value
1237   if (is_inline_klass()) {
1238       InlineKlass* vk = InlineKlass::cast(this);
1239       oop val = vk->allocate_instance(THREAD);
1240       if (HAS_PENDING_EXCEPTION) {
1241           Handle e(THREAD, PENDING_EXCEPTION);
1242           CLEAR_PENDING_EXCEPTION;
1243           {
1244               EXCEPTION_MARK;
1245               add_initialization_error(THREAD, e);
1246               // Locks object, set state, and notify all waiting threads
1247               set_initialization_state_and_notify(initialization_error, THREAD);
1248               CLEAR_PENDING_EXCEPTION;
1249           }
1250           THROW_OOP(e());
1251       }
1252       vk->set_default_value(val);
1253   }
1254 
1255   // Step 7
1256   // Next, if C is a class rather than an interface, initialize it's super class and super
1257   // interfaces.
1258   if (!is_interface()) {
1259     Klass* super_klass = super();
1260     if (super_klass != NULL && super_klass->should_be_initialized()) {
1261       super_klass->initialize(THREAD);
1262     }
1263     // If C implements any interface that declares a non-static, concrete method,
1264     // the initialization of C triggers initialization of its super interfaces.
1265     // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1266     // having a superinterface that declares, non-static, concrete methods
1267     if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1268       initialize_super_interfaces(THREAD);
1269     }
1270 
1271     // If any exceptions, complete abruptly, throwing the same exception as above.
1272     if (HAS_PENDING_EXCEPTION) {
1273       Handle e(THREAD, PENDING_EXCEPTION);
1274       CLEAR_PENDING_EXCEPTION;
1275       {
1276         EXCEPTION_MARK;
1277         add_initialization_error(THREAD, e);
1278         // Locks object, set state, and notify all waiting threads
1279         set_initialization_state_and_notify(initialization_error, THREAD);
1280         CLEAR_PENDING_EXCEPTION;
1281       }
1282       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1283       THROW_OOP(e());
1284     }
1285   }
1286 

1287   // Step 8
1288   // Initialize classes of inline fields
1289   if (EnableValhalla) {
1290     for (AllFieldStream fs(this); !fs.done(); fs.next()) {
1291       if (Signature::basic_type(fs.signature()) == T_INLINE_TYPE) {
1292         Klass* klass = get_inline_type_field_klass_or_null(fs.index());
1293         if (fs.access_flags().is_static() && klass == NULL) {
1294           klass = SystemDictionary::resolve_or_fail(field_signature(fs.index())->fundamental_name(THREAD),
1295               Handle(THREAD, class_loader()),
1296               Handle(THREAD, protection_domain()),
1297               true, THREAD);
1298           set_inline_type_field_klass(fs.index(), klass);
1299         }
1300 
1301         if (!HAS_PENDING_EXCEPTION) {
1302           assert(klass != NULL, "Must  be");
1303           InstanceKlass::cast(klass)->initialize(THREAD);
1304           if (fs.access_flags().is_static()) {
1305             if (java_mirror()->obj_field(fs.offset()) == NULL) {
1306               java_mirror()->obj_field_put(fs.offset(), InlineKlass::cast(klass)->default_value());
1307             }
1308           }
1309         }
1310 
1311         if (HAS_PENDING_EXCEPTION) {
1312           Handle e(THREAD, PENDING_EXCEPTION);
1313           CLEAR_PENDING_EXCEPTION;
1314           {
1315             EXCEPTION_MARK;
1316             add_initialization_error(THREAD, e);
1317             // Locks object, set state, and notify all waiting threads
1318             set_initialization_state_and_notify(initialization_error, THREAD);
1319             CLEAR_PENDING_EXCEPTION;
1320           }
1321           THROW_OOP(e());
1322         }
1323       }
1324     }
1325   }
1326 
1327 
1328   // Step 9
1329   {
1330     DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1331     if (class_initializer() != NULL) {
1332       // Timer includes any side effects of class initialization (resolution,
1333       // etc), but not recursive entry into call_class_initializer().
1334       PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1335                                ClassLoader::perf_class_init_selftime(),
1336                                ClassLoader::perf_classes_inited(),
1337                                jt->get_thread_stat()->perf_recursion_counts_addr(),
1338                                jt->get_thread_stat()->perf_timers_addr(),
1339                                PerfClassTraceTime::CLASS_CLINIT);
1340       call_class_initializer(THREAD);
1341     } else {
1342       // The elapsed time is so small it's not worth counting.
1343       if (UsePerfData) {
1344         ClassLoader::perf_classes_inited()->inc();
1345       }
1346       call_class_initializer(THREAD);
1347     }
1348   }
1349 
1350   // Step 10
1351   if (!HAS_PENDING_EXCEPTION) {
1352     set_initialization_state_and_notify(fully_initialized, CHECK);
1353     debug_only(vtable().verify(tty, true);)
1354   }
1355   else {
1356     // Step 11 and 12
1357     Handle e(THREAD, PENDING_EXCEPTION);
1358     CLEAR_PENDING_EXCEPTION;
1359     // JVMTI has already reported the pending exception
1360     // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1361     JvmtiExport::clear_detected_exception(jt);
1362     {
1363       EXCEPTION_MARK;
1364       add_initialization_error(THREAD, e);
1365       set_initialization_state_and_notify(initialization_error, THREAD);
1366       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
1367       // JVMTI has already reported the pending exception
1368       // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1369       JvmtiExport::clear_detected_exception(jt);
1370     }
1371     DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1372     if (e->is_a(vmClasses::Error_klass())) {
1373       THROW_OOP(e());
1374     } else {
1375       JavaCallArguments args(e);
1376       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
1377                 vmSymbols::throwable_void_signature(),
1378                 &args);
1379     }
1380   }
1381   DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1382 }
1383 
1384 
1385 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1386   Handle h_init_lock(THREAD, init_lock());
1387   if (h_init_lock() != NULL) {
1388     ObjectLocker ol(h_init_lock, THREAD);
1389     set_init_thread(NULL); // reset _init_thread before changing _init_state
1390     set_init_state(state);
1391     fence_and_clear_init_lock();
1392     ol.notify_all(CHECK);
1393   } else {
1394     assert(h_init_lock() != NULL, "The initialization state should never be set twice");
1395     set_init_thread(NULL); // reset _init_thread before changing _init_state
1396     set_init_state(state);
1397   }
1398 }
1399 
1400 InstanceKlass* InstanceKlass::implementor() const {
1401   InstanceKlass* volatile* ik = adr_implementor();
1402   if (ik == NULL) {
1403     return NULL;
1404   } else {
1405     // This load races with inserts, and therefore needs acquire.
1406     InstanceKlass* ikls = Atomic::load_acquire(ik);
1407     if (ikls != NULL && !ikls->is_loader_alive()) {
1408       return NULL;  // don't return unloaded class
1409     } else {
1410       return ikls;
1411     }
1412   }
1413 }
1414 
1415 
1416 void InstanceKlass::set_implementor(InstanceKlass* ik) {
1417   assert_locked_or_safepoint(Compile_lock);
1418   assert(is_interface(), "not interface");
1419   InstanceKlass* volatile* addr = adr_implementor();
1420   assert(addr != NULL, "null addr");
1421   if (addr != NULL) {
1422     Atomic::release_store(addr, ik);
1423   }
1424 }
1425 
1426 int  InstanceKlass::nof_implementors() const {
1427   InstanceKlass* ik = implementor();
1428   if (ik == NULL) {
1429     return 0;
1430   } else if (ik != this) {
1431     return 1;
1432   } else {
1433     return 2;
1434   }
1435 }
1436 
1437 // The embedded _implementor field can only record one implementor.
1438 // When there are more than one implementors, the _implementor field
1439 // is set to the interface Klass* itself. Following are the possible
1440 // values for the _implementor field:
1441 //   NULL                  - no implementor
1442 //   implementor Klass*    - one implementor
1443 //   self                  - more than one implementor
1444 //
1445 // The _implementor field only exists for interfaces.
1446 void InstanceKlass::add_implementor(InstanceKlass* ik) {
1447   if (Universe::is_fully_initialized()) {
1448     assert_lock_strong(Compile_lock);
1449   }
1450   assert(is_interface(), "not interface");
1451   // Filter out my subinterfaces.
1452   // (Note: Interfaces are never on the subklass list.)
1453   if (ik->is_interface()) return;
1454 
1455   // Filter out subclasses whose supers already implement me.
1456   // (Note: CHA must walk subclasses of direct implementors
1457   // in order to locate indirect implementors.)
1458   InstanceKlass* super_ik = ik->java_super();
1459   if (super_ik != NULL && super_ik->implements_interface(this))
1460     // We only need to check one immediate superclass, since the
1461     // implements_interface query looks at transitive_interfaces.
1462     // Any supers of the super have the same (or fewer) transitive_interfaces.
1463     return;
1464 
1465   InstanceKlass* iklass = implementor();
1466   if (iklass == NULL) {
1467     set_implementor(ik);
1468   } else if (iklass != this && iklass != ik) {
1469     // There is already an implementor. Use itself as an indicator of
1470     // more than one implementors.
1471     set_implementor(this);
1472   }
1473 
1474   // The implementor also implements the transitive_interfaces
1475   for (int index = 0; index < local_interfaces()->length(); index++) {
1476     local_interfaces()->at(index)->add_implementor(ik);
1477   }
1478 }
1479 
1480 void InstanceKlass::init_implementor() {
1481   if (is_interface()) {
1482     set_implementor(NULL);
1483   }
1484 }
1485 
1486 
1487 void InstanceKlass::process_interfaces() {
1488   // link this class into the implementors list of every interface it implements
1489   for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
1490     assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
1491     InstanceKlass* interf = local_interfaces()->at(i);
1492     assert(interf->is_interface(), "expected interface");
1493     interf->add_implementor(this);
1494   }
1495 }
1496 
1497 bool InstanceKlass::can_be_primary_super_slow() const {
1498   if (is_interface())
1499     return false;
1500   else
1501     return Klass::can_be_primary_super_slow();
1502 }
1503 
1504 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots,
1505                                                                Array<InstanceKlass*>* transitive_interfaces) {
1506   // The secondaries are the implemented interfaces.
1507   Array<InstanceKlass*>* interfaces = transitive_interfaces;
1508   int num_secondaries = num_extra_slots + interfaces->length();
1509   if (num_secondaries == 0) {
1510     // Must share this for correct bootstrapping!
1511     set_secondary_supers(Universe::the_empty_klass_array());
1512     return NULL;
1513   } else if (num_extra_slots == 0) {
1514     // The secondary super list is exactly the same as the transitive interfaces, so
1515     // let's use it instead of making a copy.
1516     // Redefine classes has to be careful not to delete this!
1517     // We need the cast because Array<Klass*> is NOT a supertype of Array<InstanceKlass*>,
1518     // (but it's safe to do here because we won't write into _secondary_supers from this point on).
1519     set_secondary_supers((Array<Klass*>*)(address)interfaces);
1520     return NULL;
1521   } else {
1522     // Copy transitive interfaces to a temporary growable array to be constructed
1523     // into the secondary super list with extra slots.
1524     GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
1525     for (int i = 0; i < interfaces->length(); i++) {
1526       secondaries->push(interfaces->at(i));
1527     }
1528     return secondaries;
1529   }
1530 }
1531 
1532 bool InstanceKlass::implements_interface(Klass* k) const {
1533   if (this == k) return true;
1534   assert(k->is_interface(), "should be an interface class");
1535   for (int i = 0; i < transitive_interfaces()->length(); i++) {
1536     if (transitive_interfaces()->at(i) == k) {
1537       return true;
1538     }
1539   }
1540   return false;
1541 }
1542 
1543 bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
1544   // Verify direct super interface
1545   if (this == k) return true;
1546   assert(k->is_interface(), "should be an interface class");
1547   for (int i = 0; i < local_interfaces()->length(); i++) {
1548     if (local_interfaces()->at(i) == k) {
1549       return true;
1550     }
1551   }
1552   return false;
1553 }
1554 
1555 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
1556   check_array_allocation_length(length, arrayOopDesc::max_array_length(T_OBJECT), CHECK_NULL);
1557   int size = objArrayOopDesc::object_size(length);
1558   Klass* ak = array_klass(n, CHECK_NULL);
1559   objArrayOop o = (objArrayOop)Universe::heap()->array_allocate(ak, size, length,
1560                                                                 /* do_zero */ true, CHECK_NULL);
1561   return o;
1562 }
1563 
1564 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
1565   if (TraceFinalizerRegistration) {
1566     tty->print("Registered ");
1567     i->print_value_on(tty);
1568     tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", p2i(i));
1569   }
1570   instanceHandle h_i(THREAD, i);
1571   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1572   JavaValue result(T_VOID);
1573   JavaCallArguments args(h_i);
1574   methodHandle mh (THREAD, Universe::finalizer_register_method());
1575   JavaCalls::call(&result, mh, &args, CHECK_NULL);
1576   return h_i();
1577 }
1578 
1579 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1580   bool has_finalizer_flag = has_finalizer(); // Query before possible GC
1581   int size = size_helper();  // Query before forming handle.
1582 
1583   instanceOop i;
1584 
1585   i = (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);
1586   if (has_finalizer_flag && !RegisterFinalizersAtInit) {
1587     i = register_finalizer(i, CHECK_NULL);
1588   }
1589   return i;
1590 }
1591 
1592 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1593   return instanceHandle(THREAD, allocate_instance(THREAD));
1594 }
1595 
1596 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1597   if (is_interface() || is_abstract()) {
1598     ResourceMark rm(THREAD);
1599     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1600               : vmSymbols::java_lang_InstantiationException(), external_name());
1601   }
1602   if (this == vmClasses::Class_klass()) {
1603     ResourceMark rm(THREAD);
1604     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1605               : vmSymbols::java_lang_IllegalAccessException(), external_name());
1606   }
1607 }
1608 
1609 Klass* InstanceKlass::array_klass(int n, TRAPS) {
1610   // Need load-acquire for lock-free read
1611   if (array_klasses_acquire() == NULL) {
1612     ResourceMark rm(THREAD);
1613     JavaThread *jt = THREAD;
1614     {
1615       // Atomic creation of array_klasses
1616       MutexLocker ma(THREAD, MultiArray_lock);
1617 
1618       // Check if update has already taken place
1619       if (array_klasses() == NULL) {
1620         ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this,
1621                                                                   false, false, CHECK_NULL);
1622         // use 'release' to pair with lock-free load
1623         release_set_array_klasses(k);
1624       }
1625     }
1626   }
1627   // array_klasses() will always be set at this point
1628   ArrayKlass* ak = array_klasses();
1629   return ak->array_klass(n, THREAD);
1630 }
1631 
1632 Klass* InstanceKlass::array_klass_or_null(int n) {
1633   // Need load-acquire for lock-free read
1634   ArrayKlass* ak = array_klasses_acquire();
1635   if (ak == NULL) {
1636     return NULL;
1637   } else {
1638     return ak->array_klass_or_null(n);
1639   }
1640 }
1641 
1642 Klass* InstanceKlass::array_klass(TRAPS) {
1643   return array_klass(1, THREAD);
1644 }
1645 
1646 Klass* InstanceKlass::array_klass_or_null() {
1647   return array_klass_or_null(1);
1648 }
1649 
1650 static int call_class_initializer_counter = 0;   // for debugging
1651 
1652 Method* InstanceKlass::class_initializer() const {
1653   Method* clinit = find_method(
1654       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1655   if (clinit != NULL && clinit->is_class_initializer()) {
1656     return clinit;
1657   }
1658   return NULL;
1659 }
1660 
1661 void InstanceKlass::call_class_initializer(TRAPS) {
1662   if (ReplayCompiles &&
1663       (ReplaySuppressInitializers == 1 ||
1664        (ReplaySuppressInitializers >= 2 && class_loader() != NULL))) {
1665     // Hide the existence of the initializer for the purpose of replaying the compile
1666     return;
1667   }
1668 
1669   methodHandle h_method(THREAD, class_initializer());
1670   assert(!is_initialized(), "we cannot initialize twice");
1671   LogTarget(Info, class, init) lt;
1672   if (lt.is_enabled()) {
1673     ResourceMark rm(THREAD);
1674     LogStream ls(lt);
1675     ls.print("%d Initializing ", call_class_initializer_counter++);
1676     name()->print_value_on(&ls);
1677     ls.print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", p2i(this));
1678   }
1679   if (h_method() != NULL) {
1680     JavaCallArguments args; // No arguments
1681     JavaValue result(T_VOID);
1682     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1683   }
1684 }
1685 
1686 
1687 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1688   InterpreterOopMap* entry_for) {
1689   // Lazily create the _oop_map_cache at first request
1690   // Lock-free access requires load_acquire.
1691   OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache);
1692   if (oop_map_cache == NULL) {
1693     MutexLocker x(OopMapCacheAlloc_lock,  Mutex::_no_safepoint_check_flag);
1694     // Check if _oop_map_cache was allocated while we were waiting for this lock
1695     if ((oop_map_cache = _oop_map_cache) == NULL) {
1696       oop_map_cache = new OopMapCache();
1697       // Ensure _oop_map_cache is stable, since it is examined without a lock
1698       Atomic::release_store(&_oop_map_cache, oop_map_cache);
1699     }
1700   }
1701   // _oop_map_cache is constant after init; lookup below does its own locking.
1702   oop_map_cache->lookup(method, bci, entry_for);
1703 }
1704 





1705 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1706   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1707     Symbol* f_name = fs.name();
1708     Symbol* f_sig  = fs.signature();
1709     if (f_name == name && f_sig == sig) {
1710       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1711       return true;
1712     }
1713   }
1714   return false;
1715 }
1716 
1717 
1718 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1719   const int n = local_interfaces()->length();
1720   for (int i = 0; i < n; i++) {
1721     Klass* intf1 = local_interfaces()->at(i);
1722     assert(intf1->is_interface(), "just checking type");
1723     // search for field in current interface
1724     if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
1725       assert(fd->is_static(), "interface field must be static");
1726       return intf1;
1727     }
1728     // search for field in direct superinterfaces
1729     Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
1730     if (intf2 != NULL) return intf2;
1731   }
1732   // otherwise field lookup fails
1733   return NULL;
1734 }
1735 
1736 
1737 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1738   // search order according to newest JVM spec (5.4.3.2, p.167).
1739   // 1) search for field in current klass
1740   if (find_local_field(name, sig, fd)) {
1741     return const_cast<InstanceKlass*>(this);
1742   }
1743   // 2) search for field recursively in direct superinterfaces
1744   { Klass* intf = find_interface_field(name, sig, fd);
1745     if (intf != NULL) return intf;
1746   }
1747   // 3) apply field lookup recursively if superclass exists
1748   { Klass* supr = super();
1749     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
1750   }
1751   // 4) otherwise field lookup fails
1752   return NULL;
1753 }
1754 
1755 
1756 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1757   // search order according to newest JVM spec (5.4.3.2, p.167).
1758   // 1) search for field in current klass
1759   if (find_local_field(name, sig, fd)) {
1760     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1761   }
1762   // 2) search for field recursively in direct superinterfaces
1763   if (is_static) {
1764     Klass* intf = find_interface_field(name, sig, fd);
1765     if (intf != NULL) return intf;
1766   }
1767   // 3) apply field lookup recursively if superclass exists
1768   { Klass* supr = super();
1769     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
1770   }
1771   // 4) otherwise field lookup fails
1772   return NULL;
1773 }
1774 
1775 bool InstanceKlass::contains_field_offset(int offset) {
1776   if (this->is_inline_klass()) {
1777     InlineKlass* vk = InlineKlass::cast(this);
1778     return offset >= vk->first_field_offset() && offset < (vk->first_field_offset() + vk->get_exact_size_in_bytes());
1779   } else {
1780     fieldDescriptor fd;
1781     return find_field_from_offset(offset, false, &fd);
1782   }
1783 }
1784 
1785 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1786   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1787     if (fs.offset() == offset) {
1788       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1789       if (fd->is_static() == is_static) return true;
1790     }
1791   }
1792   return false;
1793 }
1794 
1795 
1796 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1797   Klass* klass = const_cast<InstanceKlass*>(this);
1798   while (klass != NULL) {
1799     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
1800       return true;
1801     }
1802     klass = klass->super();
1803   }
1804   return false;
1805 }
1806 
1807 
1808 void InstanceKlass::methods_do(void f(Method* method)) {
1809   // Methods aren't stable until they are loaded.  This can be read outside
1810   // a lock through the ClassLoaderData for profiling
1811   if (!is_loaded()) {
1812     return;
1813   }
1814 
1815   int len = methods()->length();
1816   for (int index = 0; index < len; index++) {
1817     Method* m = methods()->at(index);
1818     assert(m->is_method(), "must be method");
1819     f(m);
1820   }
1821 }
1822 
1823 
1824 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
1825   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1826     if (fs.access_flags().is_static()) {
1827       fieldDescriptor& fd = fs.field_descriptor();
1828       cl->do_field(&fd);
1829     }
1830   }
1831 }
1832 
1833 
1834 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
1835   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1836     if (fs.access_flags().is_static()) {
1837       fieldDescriptor& fd = fs.field_descriptor();
1838       f(&fd, mirror, CHECK);
1839     }
1840   }
1841 }
1842 
1843 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
1844   InstanceKlass* super = superklass();
1845   if (super != NULL) {
1846     super->do_nonstatic_fields(cl);
1847   }
1848   fieldDescriptor fd;
1849   int length = java_fields_count();
1850   for (int i = 0; i < length; i += 1) {
1851     fd.reinitialize(this, i);
1852     if (!fd.is_static()) {
1853       cl->do_field(&fd);
1854     }
1855   }
1856 }
1857 
1858 // first in Pair is offset, second is index.
1859 static int compare_fields_by_offset(Pair<int,int>* a, Pair<int,int>* b) {
1860   return a->first - b->first;
1861 }
1862 
1863 void InstanceKlass::print_nonstatic_fields(FieldClosure* cl) {
1864   InstanceKlass* super = superklass();
1865   if (super != NULL) {
1866     super->print_nonstatic_fields(cl);
1867   }
1868   ResourceMark rm;
1869   fieldDescriptor fd;
1870   // In DebugInfo nonstatic fields are sorted by offset.
1871   GrowableArray<Pair<int,int> > fields_sorted;
1872   int i = 0;
1873   for (AllFieldStream fs(this); !fs.done(); fs.next()) {
1874     if (!fs.access_flags().is_static()) {
1875       fd = fs.field_descriptor();
1876       Pair<int,int> f(fs.offset(), fs.index());
1877       fields_sorted.push(f);
1878       i++;
1879     }
1880   }
1881   if (i > 0) {
1882     int length = i;
1883     assert(length == fields_sorted.length(), "duh");
1884     // _sort_Fn is defined in growableArray.hpp.
1885     fields_sorted.sort(compare_fields_by_offset);
1886     for (int i = 0; i < length; i++) {
1887       fd.reinitialize(this, fields_sorted.at(i).second);
1888       assert(!fd.is_static() && fd.offset() == fields_sorted.at(i).first, "only nonstatic fields");
1889       cl->do_field(&fd);
1890     }
1891   }
1892 }
1893 
1894 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
1895   if (array_klasses() != NULL)
1896     array_klasses()->array_klasses_do(f, THREAD);
1897 }
1898 
1899 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
1900   if (array_klasses() != NULL)
1901     array_klasses()->array_klasses_do(f);
1902 }
1903 
1904 #ifdef ASSERT
1905 static int linear_search(const Array<Method*>* methods,
1906                          const Symbol* name,
1907                          const Symbol* signature) {
1908   const int len = methods->length();
1909   for (int index = 0; index < len; index++) {
1910     const Method* const m = methods->at(index);
1911     assert(m->is_method(), "must be method");
1912     if (m->signature() == signature && m->name() == name) {
1913        return index;
1914     }
1915   }
1916   return -1;
1917 }
1918 #endif
1919 
1920 bool InstanceKlass::_disable_method_binary_search = false;
1921 
1922 NOINLINE int linear_search(const Array<Method*>* methods, const Symbol* name) {
1923   int len = methods->length();
1924   int l = 0;
1925   int h = len - 1;
1926   while (l <= h) {
1927     Method* m = methods->at(l);
1928     if (m->name() == name) {
1929       return l;
1930     }
1931     l++;
1932   }
1933   return -1;
1934 }
1935 
1936 inline int InstanceKlass::quick_search(const Array<Method*>* methods, const Symbol* name) {
1937   if (_disable_method_binary_search) {
1938     assert(DynamicDumpSharedSpaces, "must be");
1939     // At the final stage of dynamic dumping, the methods array may not be sorted
1940     // by ascending addresses of their names, so we can't use binary search anymore.
1941     // However, methods with the same name are still laid out consecutively inside the
1942     // methods array, so let's look for the first one that matches.
1943     return linear_search(methods, name);
1944   }
1945 
1946   int len = methods->length();
1947   int l = 0;
1948   int h = len - 1;
1949 
1950   // methods are sorted by ascending addresses of their names, so do binary search
1951   while (l <= h) {
1952     int mid = (l + h) >> 1;
1953     Method* m = methods->at(mid);
1954     assert(m->is_method(), "must be method");
1955     int res = m->name()->fast_compare(name);
1956     if (res == 0) {
1957       return mid;
1958     } else if (res < 0) {
1959       l = mid + 1;
1960     } else {
1961       h = mid - 1;
1962     }
1963   }
1964   return -1;
1965 }
1966 
1967 // find_method looks up the name/signature in the local methods array
1968 Method* InstanceKlass::find_method(const Symbol* name,
1969                                    const Symbol* signature) const {
1970   return find_method_impl(name, signature,
1971                           OverpassLookupMode::find,
1972                           StaticLookupMode::find,
1973                           PrivateLookupMode::find);
1974 }
1975 
1976 Method* InstanceKlass::find_method_impl(const Symbol* name,
1977                                         const Symbol* signature,
1978                                         OverpassLookupMode overpass_mode,
1979                                         StaticLookupMode static_mode,
1980                                         PrivateLookupMode private_mode) const {
1981   return InstanceKlass::find_method_impl(methods(),
1982                                          name,
1983                                          signature,
1984                                          overpass_mode,
1985                                          static_mode,
1986                                          private_mode);
1987 }
1988 
1989 // find_instance_method looks up the name/signature in the local methods array
1990 // and skips over static methods
1991 Method* InstanceKlass::find_instance_method(const Array<Method*>* methods,
1992                                             const Symbol* name,
1993                                             const Symbol* signature,
1994                                             PrivateLookupMode private_mode) {
1995   Method* const meth = InstanceKlass::find_method_impl(methods,
1996                                                  name,
1997                                                  signature,
1998                                                  OverpassLookupMode::find,
1999                                                  StaticLookupMode::skip,
2000                                                  private_mode);
2001   assert(((meth == NULL) || !meth->is_static()),
2002     "find_instance_method should have skipped statics");
2003   return meth;
2004 }
2005 
2006 // find_instance_method looks up the name/signature in the local methods array
2007 // and skips over static methods
2008 Method* InstanceKlass::find_instance_method(const Symbol* name,
2009                                             const Symbol* signature,
2010                                             PrivateLookupMode private_mode) const {
2011   return InstanceKlass::find_instance_method(methods(), name, signature, private_mode);
2012 }
2013 
2014 // Find looks up the name/signature in the local methods array
2015 // and filters on the overpass, static and private flags
2016 // This returns the first one found
2017 // note that the local methods array can have up to one overpass, one static
2018 // and one instance (private or not) with the same name/signature
2019 Method* InstanceKlass::find_local_method(const Symbol* name,
2020                                          const Symbol* signature,
2021                                          OverpassLookupMode overpass_mode,
2022                                          StaticLookupMode static_mode,
2023                                          PrivateLookupMode private_mode) const {
2024   return InstanceKlass::find_method_impl(methods(),
2025                                          name,
2026                                          signature,
2027                                          overpass_mode,
2028                                          static_mode,
2029                                          private_mode);
2030 }
2031 
2032 // Find looks up the name/signature in the local methods array
2033 // and filters on the overpass, static and private flags
2034 // This returns the first one found
2035 // note that the local methods array can have up to one overpass, one static
2036 // and one instance (private or not) with the same name/signature
2037 Method* InstanceKlass::find_local_method(const Array<Method*>* methods,
2038                                          const Symbol* name,
2039                                          const Symbol* signature,
2040                                          OverpassLookupMode overpass_mode,
2041                                          StaticLookupMode static_mode,
2042                                          PrivateLookupMode private_mode) {
2043   return InstanceKlass::find_method_impl(methods,
2044                                          name,
2045                                          signature,
2046                                          overpass_mode,
2047                                          static_mode,
2048                                          private_mode);
2049 }
2050 
2051 Method* InstanceKlass::find_method(const Array<Method*>* methods,
2052                                    const Symbol* name,
2053                                    const Symbol* signature) {
2054   return InstanceKlass::find_method_impl(methods,
2055                                          name,
2056                                          signature,
2057                                          OverpassLookupMode::find,
2058                                          StaticLookupMode::find,
2059                                          PrivateLookupMode::find);
2060 }
2061 
2062 Method* InstanceKlass::find_method_impl(const Array<Method*>* methods,
2063                                         const Symbol* name,
2064                                         const Symbol* signature,
2065                                         OverpassLookupMode overpass_mode,
2066                                         StaticLookupMode static_mode,
2067                                         PrivateLookupMode private_mode) {
2068   int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode);
2069   return hit >= 0 ? methods->at(hit): NULL;
2070 }
2071 
2072 // true if method matches signature and conforms to skipping_X conditions.
2073 static bool method_matches(const Method* m,
2074                            const Symbol* signature,
2075                            bool skipping_overpass,
2076                            bool skipping_static,
2077                            bool skipping_private) {
2078   return ((m->signature() == signature) &&
2079     (!skipping_overpass || !m->is_overpass()) &&
2080     (!skipping_static || !m->is_static()) &&
2081     (!skipping_private || !m->is_private()));
2082 }
2083 
2084 // Used directly for default_methods to find the index into the
2085 // default_vtable_indices, and indirectly by find_method
2086 // find_method_index looks in the local methods array to return the index
2087 // of the matching name/signature. If, overpass methods are being ignored,
2088 // the search continues to find a potential non-overpass match.  This capability
2089 // is important during method resolution to prefer a static method, for example,
2090 // over an overpass method.
2091 // There is the possibility in any _method's array to have the same name/signature
2092 // for a static method, an overpass method and a local instance method
2093 // To correctly catch a given method, the search criteria may need
2094 // to explicitly skip the other two. For local instance methods, it
2095 // is often necessary to skip private methods
2096 int InstanceKlass::find_method_index(const Array<Method*>* methods,
2097                                      const Symbol* name,
2098                                      const Symbol* signature,
2099                                      OverpassLookupMode overpass_mode,
2100                                      StaticLookupMode static_mode,
2101                                      PrivateLookupMode private_mode) {
2102   const bool skipping_overpass = (overpass_mode == OverpassLookupMode::skip);
2103   const bool skipping_static = (static_mode == StaticLookupMode::skip);
2104   const bool skipping_private = (private_mode == PrivateLookupMode::skip);
2105   const int hit = quick_search(methods, name);
2106   if (hit != -1) {
2107     const Method* const m = methods->at(hit);
2108 
2109     // Do linear search to find matching signature.  First, quick check
2110     // for common case, ignoring overpasses if requested.
2111     if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
2112       return hit;
2113     }
2114 
2115     // search downwards through overloaded methods
2116     int i;
2117     for (i = hit - 1; i >= 0; --i) {
2118         const Method* const m = methods->at(i);
2119         assert(m->is_method(), "must be method");
2120         if (m->name() != name) {
2121           break;
2122         }
2123         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
2124           return i;
2125         }
2126     }
2127     // search upwards
2128     for (i = hit + 1; i < methods->length(); ++i) {
2129         const Method* const m = methods->at(i);
2130         assert(m->is_method(), "must be method");
2131         if (m->name() != name) {
2132           break;
2133         }
2134         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
2135           return i;
2136         }
2137     }
2138     // not found
2139 #ifdef ASSERT
2140     const int index = (skipping_overpass || skipping_static || skipping_private) ? -1 :
2141       linear_search(methods, name, signature);
2142     assert(-1 == index, "binary search should have found entry %d", index);
2143 #endif
2144   }
2145   return -1;
2146 }
2147 
2148 int InstanceKlass::find_method_by_name(const Symbol* name, int* end) const {
2149   return find_method_by_name(methods(), name, end);
2150 }
2151 
2152 int InstanceKlass::find_method_by_name(const Array<Method*>* methods,
2153                                        const Symbol* name,
2154                                        int* end_ptr) {
2155   assert(end_ptr != NULL, "just checking");
2156   int start = quick_search(methods, name);
2157   int end = start + 1;
2158   if (start != -1) {
2159     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
2160     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
2161     *end_ptr = end;
2162     return start;
2163   }
2164   return -1;
2165 }
2166 
2167 // uncached_lookup_method searches both the local class methods array and all
2168 // superclasses methods arrays, skipping any overpass methods in superclasses,
2169 // and possibly skipping private methods.
2170 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2171                                               const Symbol* signature,
2172                                               OverpassLookupMode overpass_mode,
2173                                               PrivateLookupMode private_mode) const {
2174   OverpassLookupMode overpass_local_mode = overpass_mode;
2175   const Klass* klass = this;
2176   while (klass != NULL) {
2177     Method* const method = InstanceKlass::cast(klass)->find_method_impl(name,
2178                                                                         signature,
2179                                                                         overpass_local_mode,
2180                                                                         StaticLookupMode::find,
2181                                                                         private_mode);
2182     if (method != NULL) {
2183       return method;
2184     }
2185     if (name == vmSymbols::object_initializer_name()) {
2186       break;  // <init> is never inherited, not even as a static factory
2187     }
2188     klass = klass->super();
2189     overpass_local_mode = OverpassLookupMode::skip;   // Always ignore overpass methods in superclasses
2190   }
2191   return NULL;
2192 }
2193 
2194 #ifdef ASSERT
2195 // search through class hierarchy and return true if this class or
2196 // one of the superclasses was redefined
2197 bool InstanceKlass::has_redefined_this_or_super() const {
2198   const Klass* klass = this;
2199   while (klass != NULL) {
2200     if (InstanceKlass::cast(klass)->has_been_redefined()) {
2201       return true;
2202     }
2203     klass = klass->super();
2204   }
2205   return false;
2206 }
2207 #endif
2208 
2209 // lookup a method in the default methods list then in all transitive interfaces
2210 // Do NOT return private or static methods
2211 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
2212                                                          Symbol* signature) const {
2213   Method* m = NULL;
2214   if (default_methods() != NULL) {
2215     m = find_method(default_methods(), name, signature);
2216   }
2217   // Look up interfaces
2218   if (m == NULL) {
2219     m = lookup_method_in_all_interfaces(name, signature, DefaultsLookupMode::find);
2220   }
2221   return m;
2222 }
2223 
2224 // lookup a method in all the interfaces that this class implements
2225 // Do NOT return private or static methods, new in JDK8 which are not externally visible
2226 // They should only be found in the initial InterfaceMethodRef
2227 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
2228                                                        Symbol* signature,
2229                                                        DefaultsLookupMode defaults_mode) const {
2230   Array<InstanceKlass*>* all_ifs = transitive_interfaces();
2231   int num_ifs = all_ifs->length();
2232   InstanceKlass *ik = NULL;
2233   for (int i = 0; i < num_ifs; i++) {
2234     ik = all_ifs->at(i);
2235     Method* m = ik->lookup_method(name, signature);
2236     if (m != NULL && m->is_public() && !m->is_static() &&
2237         ((defaults_mode != DefaultsLookupMode::skip) || !m->is_default_method())) {
2238       return m;
2239     }
2240   }
2241   return NULL;
2242 }
2243 
2244 /* jni_id_for_impl for jfieldIds only */
2245 JNIid* InstanceKlass::jni_id_for_impl(int offset) {
2246   MutexLocker ml(JfieldIdCreation_lock);
2247   // Retry lookup after we got the lock
2248   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
2249   if (probe == NULL) {
2250     // Slow case, allocate new static field identifier
2251     probe = new JNIid(this, offset, jni_ids());
2252     set_jni_ids(probe);
2253   }
2254   return probe;
2255 }
2256 
2257 
2258 /* jni_id_for for jfieldIds only */
2259 JNIid* InstanceKlass::jni_id_for(int offset) {
2260   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
2261   if (probe == NULL) {
2262     probe = jni_id_for_impl(offset);
2263   }
2264   return probe;
2265 }
2266 
2267 u2 InstanceKlass::enclosing_method_data(int offset) const {
2268   const Array<jushort>* const inner_class_list = inner_classes();
2269   if (inner_class_list == NULL) {
2270     return 0;
2271   }
2272   const int length = inner_class_list->length();
2273   if (length % inner_class_next_offset == 0) {
2274     return 0;
2275   }
2276   const int index = length - enclosing_method_attribute_size;
2277   assert(offset < enclosing_method_attribute_size, "invalid offset");
2278   return inner_class_list->at(index + offset);
2279 }
2280 
2281 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
2282                                                  u2 method_index) {
2283   Array<jushort>* inner_class_list = inner_classes();
2284   assert (inner_class_list != NULL, "_inner_classes list is not set up");
2285   int length = inner_class_list->length();
2286   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
2287     int index = length - enclosing_method_attribute_size;
2288     inner_class_list->at_put(
2289       index + enclosing_method_class_index_offset, class_index);
2290     inner_class_list->at_put(
2291       index + enclosing_method_method_index_offset, method_index);
2292   }
2293 }
2294 
2295 // Lookup or create a jmethodID.
2296 // This code is called by the VMThread and JavaThreads so the
2297 // locking has to be done very carefully to avoid deadlocks
2298 // and/or other cache consistency problems.
2299 //
2300 jmethodID InstanceKlass::get_jmethod_id(const methodHandle& method_h) {
2301   size_t idnum = (size_t)method_h->method_idnum();
2302   jmethodID* jmeths = methods_jmethod_ids_acquire();
2303   size_t length = 0;
2304   jmethodID id = NULL;
2305 
2306   // We use a double-check locking idiom here because this cache is
2307   // performance sensitive. In the normal system, this cache only
2308   // transitions from NULL to non-NULL which is safe because we use
2309   // release_set_methods_jmethod_ids() to advertise the new cache.
2310   // A partially constructed cache should never be seen by a racing
2311   // thread. We also use release_store() to save a new jmethodID
2312   // in the cache so a partially constructed jmethodID should never be
2313   // seen either. Cache reads of existing jmethodIDs proceed without a
2314   // lock, but cache writes of a new jmethodID requires uniqueness and
2315   // creation of the cache itself requires no leaks so a lock is
2316   // generally acquired in those two cases.
2317   //
2318   // If the RedefineClasses() API has been used, then this cache can
2319   // grow and we'll have transitions from non-NULL to bigger non-NULL.
2320   // Cache creation requires no leaks and we require safety between all
2321   // cache accesses and freeing of the old cache so a lock is generally
2322   // acquired when the RedefineClasses() API has been used.
2323 
2324   if (jmeths != NULL) {
2325     // the cache already exists
2326     if (!idnum_can_increment()) {
2327       // the cache can't grow so we can just get the current values
2328       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
2329     } else {
2330       // cache can grow so we have to be more careful
2331       if (Threads::number_of_threads() == 0 ||
2332           SafepointSynchronize::is_at_safepoint()) {
2333         // we're single threaded or at a safepoint - no locking needed
2334         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
2335       } else {
2336         MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag);
2337         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
2338       }
2339     }
2340   }
2341   // implied else:
2342   // we need to allocate a cache so default length and id values are good
2343 
2344   if (jmeths == NULL ||   // no cache yet
2345       length <= idnum ||  // cache is too short
2346       id == NULL) {       // cache doesn't contain entry
2347 
2348     // This function can be called by the VMThread so we have to do all
2349     // things that might block on a safepoint before grabbing the lock.
2350     // Otherwise, we can deadlock with the VMThread or have a cache
2351     // consistency issue. These vars keep track of what we might have
2352     // to free after the lock is dropped.
2353     jmethodID  to_dealloc_id     = NULL;
2354     jmethodID* to_dealloc_jmeths = NULL;
2355 
2356     // may not allocate new_jmeths or use it if we allocate it
2357     jmethodID* new_jmeths = NULL;
2358     if (length <= idnum) {
2359       // allocate a new cache that might be used
2360       size_t size = MAX2(idnum+1, (size_t)idnum_allocated_count());
2361       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
2362       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
2363       // cache size is stored in element[0], other elements offset by one
2364       new_jmeths[0] = (jmethodID)size;
2365     }
2366 
2367     // allocate a new jmethodID that might be used
2368     jmethodID new_id = NULL;
2369     if (method_h->is_old() && !method_h->is_obsolete()) {
2370       // The method passed in is old (but not obsolete), we need to use the current version
2371       Method* current_method = method_with_idnum((int)idnum);
2372       assert(current_method != NULL, "old and but not obsolete, so should exist");
2373       new_id = Method::make_jmethod_id(class_loader_data(), current_method);
2374     } else {
2375       // It is the current version of the method or an obsolete method,
2376       // use the version passed in
2377       new_id = Method::make_jmethod_id(class_loader_data(), method_h());
2378     }
2379 
2380     if (Threads::number_of_threads() == 0 ||
2381         SafepointSynchronize::is_at_safepoint()) {
2382       // we're single threaded or at a safepoint - no locking needed
2383       id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,
2384                                           &to_dealloc_id, &to_dealloc_jmeths);
2385     } else {
2386       MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag);
2387       id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,
2388                                           &to_dealloc_id, &to_dealloc_jmeths);
2389     }
2390 
2391     // The lock has been dropped so we can free resources.
2392     // Free up either the old cache or the new cache if we allocated one.
2393     if (to_dealloc_jmeths != NULL) {
2394       FreeHeap(to_dealloc_jmeths);
2395     }
2396     // free up the new ID since it wasn't needed
2397     if (to_dealloc_id != NULL) {
2398       Method::destroy_jmethod_id(class_loader_data(), to_dealloc_id);
2399     }
2400   }
2401   return id;
2402 }
2403 
2404 // Figure out how many jmethodIDs haven't been allocated, and make
2405 // sure space for them is pre-allocated.  This makes getting all
2406 // method ids much, much faster with classes with more than 8
2407 // methods, and has a *substantial* effect on performance with jvmti
2408 // code that loads all jmethodIDs for all classes.
2409 void InstanceKlass::ensure_space_for_methodids(int start_offset) {
2410   int new_jmeths = 0;
2411   int length = methods()->length();
2412   for (int index = start_offset; index < length; index++) {
2413     Method* m = methods()->at(index);
2414     jmethodID id = m->find_jmethod_id_or_null();
2415     if (id == NULL) {
2416       new_jmeths++;
2417     }
2418   }
2419   if (new_jmeths != 0) {
2420     Method::ensure_jmethod_ids(class_loader_data(), new_jmeths);
2421   }
2422 }
2423 
2424 // Common code to fetch the jmethodID from the cache or update the
2425 // cache with the new jmethodID. This function should never do anything
2426 // that causes the caller to go to a safepoint or we can deadlock with
2427 // the VMThread or have cache consistency issues.
2428 //
2429 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
2430             size_t idnum, jmethodID new_id,
2431             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
2432             jmethodID** to_dealloc_jmeths_p) {
2433   assert(new_id != NULL, "sanity check");
2434   assert(to_dealloc_id_p != NULL, "sanity check");
2435   assert(to_dealloc_jmeths_p != NULL, "sanity check");
2436   assert(Threads::number_of_threads() == 0 ||
2437          SafepointSynchronize::is_at_safepoint() ||
2438          JmethodIdCreation_lock->owned_by_self(), "sanity check");
2439 
2440   // reacquire the cache - we are locked, single threaded or at a safepoint
2441   jmethodID* jmeths = methods_jmethod_ids_acquire();
2442   jmethodID  id     = NULL;
2443   size_t     length = 0;
2444 
2445   if (jmeths == NULL ||                         // no cache yet
2446       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
2447     if (jmeths != NULL) {
2448       // copy any existing entries from the old cache
2449       for (size_t index = 0; index < length; index++) {
2450         new_jmeths[index+1] = jmeths[index+1];
2451       }
2452       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
2453     }
2454     release_set_methods_jmethod_ids(jmeths = new_jmeths);
2455   } else {
2456     // fetch jmethodID (if any) from the existing cache
2457     id = jmeths[idnum+1];
2458     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
2459   }
2460   if (id == NULL) {
2461     // No matching jmethodID in the existing cache or we have a new
2462     // cache or we just grew the cache. This cache write is done here
2463     // by the first thread to win the foot race because a jmethodID
2464     // needs to be unique once it is generally available.
2465     id = new_id;
2466 
2467     // The jmethodID cache can be read while unlocked so we have to
2468     // make sure the new jmethodID is complete before installing it
2469     // in the cache.
2470     Atomic::release_store(&jmeths[idnum+1], id);
2471   } else {
2472     *to_dealloc_id_p = new_id; // save new id for later delete
2473   }
2474   return id;
2475 }
2476 
2477 
2478 // Common code to get the jmethodID cache length and the jmethodID
2479 // value at index idnum if there is one.
2480 //
2481 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
2482        size_t idnum, size_t *length_p, jmethodID* id_p) {
2483   assert(cache != NULL, "sanity check");
2484   assert(length_p != NULL, "sanity check");
2485   assert(id_p != NULL, "sanity check");
2486 
2487   // cache size is stored in element[0], other elements offset by one
2488   *length_p = (size_t)cache[0];
2489   if (*length_p <= idnum) {  // cache is too short
2490     *id_p = NULL;
2491   } else {
2492     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
2493   }
2494 }
2495 
2496 
2497 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
2498 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
2499   size_t idnum = (size_t)method->method_idnum();
2500   jmethodID* jmeths = methods_jmethod_ids_acquire();
2501   size_t length;                                // length assigned as debugging crumb
2502   jmethodID id = NULL;
2503   if (jmeths != NULL &&                         // If there is a cache
2504       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
2505     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
2506   }
2507   return id;
2508 }
2509 
2510 inline DependencyContext InstanceKlass::dependencies() {
2511   DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);
2512   return dep_context;
2513 }
2514 
2515 int InstanceKlass::mark_dependent_nmethods(KlassDepChange& changes) {
2516   return dependencies().mark_dependent_nmethods(changes);
2517 }
2518 
2519 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2520   dependencies().add_dependent_nmethod(nm);
2521 }
2522 
2523 void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
2524   dependencies().remove_dependent_nmethod(nm);
2525 }
2526 
2527 void InstanceKlass::clean_dependency_context() {
2528   dependencies().clean_unloading_dependents();
2529 }
2530 
2531 #ifndef PRODUCT
2532 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2533   dependencies().print_dependent_nmethods(verbose);
2534 }
2535 
2536 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2537   return dependencies().is_dependent_nmethod(nm);
2538 }
2539 #endif //PRODUCT
2540 
2541 void InstanceKlass::clean_weak_instanceklass_links() {
2542   clean_implementors_list();
2543   clean_method_data();
2544 }
2545 
2546 void InstanceKlass::clean_implementors_list() {
2547   assert(is_loader_alive(), "this klass should be live");
2548   if (is_interface()) {
2549     assert (ClassUnloading, "only called for ClassUnloading");
2550     for (;;) {
2551       // Use load_acquire due to competing with inserts
2552       InstanceKlass* impl = Atomic::load_acquire(adr_implementor());
2553       if (impl != NULL && !impl->is_loader_alive()) {
2554         // NULL this field, might be an unloaded instance klass or NULL
2555         InstanceKlass* volatile* iklass = adr_implementor();
2556         if (Atomic::cmpxchg(iklass, impl, (InstanceKlass*)NULL) == impl) {
2557           // Successfully unlinking implementor.
2558           if (log_is_enabled(Trace, class, unload)) {
2559             ResourceMark rm;
2560             log_trace(class, unload)("unlinking class (implementor): %s", impl->external_name());
2561           }
2562           return;
2563         }
2564       } else {
2565         return;
2566       }
2567     }
2568   }
2569 }
2570 
2571 void InstanceKlass::clean_method_data() {
2572   for (int m = 0; m < methods()->length(); m++) {
2573     MethodData* mdo = methods()->at(m)->method_data();
2574     if (mdo != NULL) {
2575       MutexLocker ml(SafepointSynchronize::is_at_safepoint() ? NULL : mdo->extra_data_lock());
2576       mdo->clean_method_data(/*always_clean*/false);
2577     }
2578   }
2579 }
2580 
2581 void InstanceKlass::metaspace_pointers_do(MetaspaceClosure* it) {
2582   Klass::metaspace_pointers_do(it);
2583 
2584   if (log_is_enabled(Trace, cds)) {
2585     ResourceMark rm;
2586     log_trace(cds)("Iter(InstanceKlass): %p (%s)", this, external_name());
2587   }
2588 
2589   it->push(&_annotations);
2590   it->push((Klass**)&_array_klasses);
2591   if (!is_rewritten()) {
2592     it->push(&_constants, MetaspaceClosure::_writable);
2593   } else {
2594     it->push(&_constants);
2595   }
2596   it->push(&_inner_classes);
2597 #if INCLUDE_JVMTI
2598   it->push(&_previous_versions);
2599 #endif
2600   it->push(&_methods);
2601   it->push(&_default_methods);
2602   it->push(&_local_interfaces);
2603   it->push(&_transitive_interfaces);
2604   it->push(&_method_ordering);
2605   if (!is_rewritten()) {
2606     it->push(&_default_vtable_indices, MetaspaceClosure::_writable);
2607   } else {
2608     it->push(&_default_vtable_indices);
2609   }
2610   it->push(&_fields);
2611 
2612   if (itable_length() > 0) {
2613     itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2614     int method_table_offset_in_words = ioe->offset()/wordSize;
2615     int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2616                          / itableOffsetEntry::size();
2617 
2618     for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2619       if (ioe->interface_klass() != NULL) {
2620         it->push(ioe->interface_klass_addr());
2621         itableMethodEntry* ime = ioe->first_method_entry(this);
2622         int n = klassItable::method_count_for_interface(ioe->interface_klass());
2623         for (int index = 0; index < n; index ++) {
2624           it->push(ime[index].method_addr());
2625         }
2626       }
2627     }
2628   }
2629 
2630   it->push(&_nest_members);
2631   it->push(&_permitted_subclasses);
2632   it->push(&_record_components);
2633 
2634   if (has_inline_type_fields()) {
2635     for (int i = 0; i < java_fields_count(); i++) {
2636       it->push(&((Klass**)adr_inline_type_field_klasses())[i]);
2637     }
2638   }
2639 }
2640 
2641 void InstanceKlass::remove_unshareable_info() {
2642 
2643   if (is_linked()) {
2644     assert(can_be_verified_at_dumptime(), "must be");
2645     // Remember this so we can avoid walking the hierarchy at runtime.
2646     set_verified_at_dump_time();
2647   }
2648 
2649   Klass::remove_unshareable_info();
2650 
2651   if (SystemDictionaryShared::has_class_failed_verification(this)) {
2652     // Classes are attempted to link during dumping and may fail,
2653     // but these classes are still in the dictionary and class list in CLD.
2654     // If the class has failed verification, there is nothing else to remove.
2655     return;
2656   }
2657 
2658   // Reset to the 'allocated' state to prevent any premature accessing to
2659   // a shared class at runtime while the class is still being loaded and
2660   // restored. A class' init_state is set to 'loaded' at runtime when it's
2661   // being added to class hierarchy (see SystemDictionary:::add_to_hierarchy()).
2662   _init_state = allocated;
2663 
2664   { // Otherwise this needs to take out the Compile_lock.
2665     assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2666     init_implementor();
2667   }
2668 
2669   constants()->remove_unshareable_info();
2670 
2671   for (int i = 0; i < methods()->length(); i++) {
2672     Method* m = methods()->at(i);
2673     m->remove_unshareable_info();
2674   }
2675 
2676   // do array classes also.
2677   if (array_klasses() != NULL) {
2678     array_klasses()->remove_unshareable_info();
2679   }
2680 
2681   if (has_inline_type_fields()) {
2682     for (AllFieldStream fs(fields(), constants()); !fs.done(); fs.next()) {
2683       if (Signature::basic_type(fs.signature()) == T_INLINE_TYPE) {
2684         reset_inline_type_field_klass(fs.index());
2685       }
2686     }
2687   }
2688 
2689   // These are not allocated from metaspace. They are safe to set to NULL.
2690   _source_debug_extension = NULL;
2691   _dep_context = NULL;
2692   _osr_nmethods_head = NULL;
2693 #if INCLUDE_JVMTI
2694   _breakpoints = NULL;
2695   _previous_versions = NULL;
2696   _cached_class_file = NULL;
2697   _jvmti_cached_class_field_map = NULL;
2698 #endif
2699 
2700   _init_thread = NULL;
2701   _methods_jmethod_ids = NULL;
2702   _jni_ids = NULL;
2703   _oop_map_cache = NULL;
2704   // clear _nest_host to ensure re-load at runtime
2705   _nest_host = NULL;
2706   init_shared_package_entry();
2707   _dep_context_last_cleaned = 0;
2708 }
2709 
2710 void InstanceKlass::remove_java_mirror() {
2711   Klass::remove_java_mirror();
2712 
2713   // do array classes also.
2714   if (array_klasses() != NULL) {
2715     array_klasses()->remove_java_mirror();
2716   }
2717 }
2718 
2719 void InstanceKlass::init_shared_package_entry() {
2720 #if !INCLUDE_CDS_JAVA_HEAP
2721   _package_entry = NULL;
2722 #else
2723   if (!MetaspaceShared::use_full_module_graph()) {
2724     _package_entry = NULL;
2725   } else if (DynamicDumpSharedSpaces) {
2726     if (!MetaspaceShared::is_in_shared_metaspace(_package_entry)) {
2727       _package_entry = NULL;
2728     }
2729   } else {
2730     if (is_shared_unregistered_class()) {
2731       _package_entry = NULL;
2732     } else {
2733       _package_entry = PackageEntry::get_archived_entry(_package_entry);
2734     }
2735   }
2736   ArchivePtrMarker::mark_pointer((address**)&_package_entry);
2737 #endif
2738 }
2739 
2740 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
2741                                              PackageEntry* pkg_entry, TRAPS) {
2742   // SystemDictionary::add_to_hierarchy() sets the init_state to loaded
2743   // before the InstanceKlass is added to the SystemDictionary. Make
2744   // sure the current state is <loaded.
2745   assert(!is_loaded(), "invalid init state");
2746   assert(!shared_loading_failed(), "Must not try to load failed class again");
2747   set_package(loader_data, pkg_entry, CHECK);
2748   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2749 
2750   if (is_inline_klass()) {
2751     InlineKlass::cast(this)->initialize_calling_convention(CHECK);
2752   }
2753 
2754   Array<Method*>* methods = this->methods();
2755   int num_methods = methods->length();
2756   for (int index = 0; index < num_methods; ++index) {
2757     methods->at(index)->restore_unshareable_info(CHECK);
2758   }
2759 #if INCLUDE_JVMTI
2760   if (JvmtiExport::has_redefined_a_class()) {
2761     // Reinitialize vtable because RedefineClasses may have changed some
2762     // entries in this vtable for super classes so the CDS vtable might
2763     // point to old or obsolete entries.  RedefineClasses doesn't fix up
2764     // vtables in the shared system dictionary, only the main one.
2765     // It also redefines the itable too so fix that too.
2766     // First fix any default methods that point to a super class that may
2767     // have been redefined.
2768     bool trace_name_printed = false;
2769     adjust_default_methods(&trace_name_printed);
2770     vtable().initialize_vtable();
2771     itable().initialize_itable();
2772   }
2773 #endif
2774 
2775   // restore constant pool resolved references
2776   constants()->restore_unshareable_info(CHECK);
2777 
2778   if (array_klasses() != NULL) {
2779     // Array classes have null protection domain.
2780     // --> see ArrayKlass::complete_create_array_klass()
2781     array_klasses()->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);
2782   }
2783 
2784   // Initialize @ValueBased class annotation
2785   if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation()) {
2786     set_is_value_based();
2787   }
2788 }
2789 
2790 // Check if a class or any of its supertypes has a version older than 50.
2791 // CDS will not perform verification of old classes during dump time because
2792 // without changing the old verifier, the verification constraint cannot be
2793 // retrieved during dump time.
2794 // Verification of archived old classes will be performed during run time.
2795 bool InstanceKlass::can_be_verified_at_dumptime() const {
2796   if (major_version() < 50 /*JAVA_6_VERSION*/) {
2797     return false;
2798   }
2799   if (java_super() != NULL && !java_super()->can_be_verified_at_dumptime()) {
2800     return false;
2801   }
2802   Array<InstanceKlass*>* interfaces = local_interfaces();
2803   int len = interfaces->length();
2804   for (int i = 0; i < len; i++) {
2805     if (!interfaces->at(i)->can_be_verified_at_dumptime()) {
2806       return false;
2807     }
2808   }
2809   return true;
2810 }
2811 
2812 void InstanceKlass::set_shared_class_loader_type(s2 loader_type) {
2813   switch (loader_type) {
2814   case ClassLoader::BOOT_LOADER:
2815     _misc_flags |= _misc_is_shared_boot_class;
2816     break;
2817   case ClassLoader::PLATFORM_LOADER:
2818     _misc_flags |= _misc_is_shared_platform_class;
2819     break;
2820   case ClassLoader::APP_LOADER:
2821     _misc_flags |= _misc_is_shared_app_class;
2822     break;
2823   default:
2824     ShouldNotReachHere();
2825     break;
2826   }
2827 }
2828 
2829 void InstanceKlass::assign_class_loader_type() {
2830   ClassLoaderData *cld = class_loader_data();
2831   if (cld->is_boot_class_loader_data()) {
2832     set_shared_class_loader_type(ClassLoader::BOOT_LOADER);
2833   }
2834   else if (cld->is_platform_class_loader_data()) {
2835     set_shared_class_loader_type(ClassLoader::PLATFORM_LOADER);
2836   }
2837   else if (cld->is_system_class_loader_data()) {
2838     set_shared_class_loader_type(ClassLoader::APP_LOADER);
2839   }
2840 }
2841 
2842 #if INCLUDE_JVMTI
2843 static void clear_all_breakpoints(Method* m) {
2844   m->clear_all_breakpoints();
2845 }
2846 #endif
2847 
2848 void InstanceKlass::unload_class(InstanceKlass* ik) {
2849   // Release dependencies.
2850   ik->dependencies().remove_all_dependents();
2851 
2852   // notify the debugger
2853   if (JvmtiExport::should_post_class_unload()) {
2854     JvmtiExport::post_class_unload(ik);
2855   }
2856 
2857   // notify ClassLoadingService of class unload
2858   ClassLoadingService::notify_class_unloaded(ik);
2859 
2860   SystemDictionaryShared::handle_class_unloading(ik);
2861 
2862   if (log_is_enabled(Info, class, unload)) {
2863     ResourceMark rm;
2864     log_info(class, unload)("unloading class %s " INTPTR_FORMAT, ik->external_name(), p2i(ik));
2865   }
2866 
2867   Events::log_class_unloading(Thread::current(), ik);
2868 
2869 #if INCLUDE_JFR
2870   assert(ik != NULL, "invariant");
2871   EventClassUnload event;
2872   event.set_unloadedClass(ik);
2873   event.set_definingClassLoader(ik->class_loader_data());
2874   event.commit();
2875 #endif
2876 }
2877 
2878 static void method_release_C_heap_structures(Method* m) {
2879   m->release_C_heap_structures();
2880 }
2881 
2882 void InstanceKlass::release_C_heap_structures() {
2883 
2884   // Clean up C heap
2885   release_C_heap_structures_internal();
2886   constants()->release_C_heap_structures();
2887 
2888   // Deallocate and call destructors for MDO mutexes
2889   methods_do(method_release_C_heap_structures);
2890 }
2891 
2892 void InstanceKlass::release_C_heap_structures_internal() {
2893   Klass::release_C_heap_structures();
2894 
2895   // Can't release the constant pool here because the constant pool can be
2896   // deallocated separately from the InstanceKlass for default methods and
2897   // redefine classes.
2898 
2899   // Deallocate oop map cache
2900   if (_oop_map_cache != NULL) {
2901     delete _oop_map_cache;
2902     _oop_map_cache = NULL;
2903   }
2904 
2905   // Deallocate JNI identifiers for jfieldIDs
2906   JNIid::deallocate(jni_ids());
2907   set_jni_ids(NULL);
2908 
2909   jmethodID* jmeths = methods_jmethod_ids_acquire();
2910   if (jmeths != (jmethodID*)NULL) {
2911     release_set_methods_jmethod_ids(NULL);
2912     FreeHeap(jmeths);
2913   }
2914 
2915   assert(_dep_context == NULL,
2916          "dependencies should already be cleaned");
2917 
2918 #if INCLUDE_JVMTI
2919   // Deallocate breakpoint records
2920   if (breakpoints() != 0x0) {
2921     methods_do(clear_all_breakpoints);
2922     assert(breakpoints() == 0x0, "should have cleared breakpoints");
2923   }
2924 
2925   // deallocate the cached class file
2926   if (_cached_class_file != NULL) {
2927     os::free(_cached_class_file);
2928     _cached_class_file = NULL;
2929   }
2930 #endif
2931 
2932   FREE_C_HEAP_ARRAY(char, _source_debug_extension);
2933 }
2934 
2935 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
2936   if (array == NULL) {
2937     _source_debug_extension = NULL;
2938   } else {
2939     // Adding one to the attribute length in order to store a null terminator
2940     // character could cause an overflow because the attribute length is
2941     // already coded with an u4 in the classfile, but in practice, it's
2942     // unlikely to happen.
2943     assert((length+1) > length, "Overflow checking");
2944     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2945     for (int i = 0; i < length; i++) {
2946       sde[i] = array[i];
2947     }
2948     sde[length] = '\0';
2949     _source_debug_extension = sde;
2950   }
2951 }
2952 
2953 const char* InstanceKlass::signature_name() const {
2954   return signature_name_of_carrier(JVM_SIGNATURE_CLASS);
2955 }
2956 
2957 const char* InstanceKlass::signature_name_of_carrier(char c) const {
2958   int hash_len = 0;
2959   char hash_buf[40];
2960 
2961   // Get the internal name as a c string
2962   const char* src = (const char*) (name()->as_C_string());
2963   const int src_length = (int)strlen(src);
2964 
2965   char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
2966 
2967   // Add L or Q as type indicator
2968   int dest_index = 0;
2969   dest[dest_index++] = c;
2970 
2971   // Add the actual class name
2972   for (int src_index = 0; src_index < src_length; ) {
2973     dest[dest_index++] = src[src_index++];
2974   }
2975 
2976   if (is_hidden()) { // Replace the last '+' with a '.'.
2977     for (int index = (int)src_length; index > 0; index--) {
2978       if (dest[index] == '+') {
2979         dest[index] = JVM_SIGNATURE_DOT;
2980         break;
2981       }
2982     }
2983   }
2984 
2985   // If we have a hash, append it
2986   for (int hash_index = 0; hash_index < hash_len; ) {
2987     dest[dest_index++] = hash_buf[hash_index++];
2988   }
2989 
2990   // Add the semicolon and the NULL
2991   dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
2992   dest[dest_index] = '\0';
2993   return dest;
2994 }
2995 
2996 ModuleEntry* InstanceKlass::module() const {
2997   if (is_hidden() &&
2998       in_unnamed_package() &&
2999       class_loader_data()->has_class_mirror_holder()) {
3000     // For a non-strong hidden class defined to an unnamed package,
3001     // its (class held) CLD will not have an unnamed module created for it.
3002     // Two choices to find the correct ModuleEntry:
3003     // 1. If hidden class is within a nest, use nest host's module
3004     // 2. Find the unnamed module off from the class loader
3005     // For now option #2 is used since a nest host is not set until
3006     // after the instance class is created in jvm_lookup_define_class().
3007     if (class_loader_data()->is_boot_class_loader_data()) {
3008       return ClassLoaderData::the_null_class_loader_data()->unnamed_module();
3009     } else {
3010       oop module = java_lang_ClassLoader::unnamedModule(class_loader_data()->class_loader());
3011       assert(java_lang_Module::is_instance(module), "Not an instance of java.lang.Module");
3012       return java_lang_Module::module_entry(module);
3013     }
3014   }
3015 
3016   // Class is in a named package
3017   if (!in_unnamed_package()) {
3018     return _package_entry->module();
3019   }
3020 
3021   // Class is in an unnamed package, return its loader's unnamed module
3022   return class_loader_data()->unnamed_module();
3023 }
3024 
3025 void InstanceKlass::set_package(ClassLoaderData* loader_data, PackageEntry* pkg_entry, TRAPS) {
3026 
3027   // ensure java/ packages only loaded by boot or platform builtin loaders
3028   // not needed for shared class since CDS does not archive prohibited classes.
3029   if (!is_shared()) {
3030     check_prohibited_package(name(), loader_data, CHECK);
3031   }
3032 
3033   if (is_shared() && _package_entry != NULL) {
3034     if (MetaspaceShared::use_full_module_graph() && _package_entry == pkg_entry) {
3035       // we can use the saved package
3036       assert(MetaspaceShared::is_in_shared_metaspace(_package_entry), "must be");
3037       return;
3038     } else {
3039       _package_entry = NULL;
3040     }
3041   }
3042 
3043   // ClassLoader::package_from_class_name has already incremented the refcount of the symbol
3044   // it returns, so we need to decrement it when the current function exits.
3045   TempNewSymbol from_class_name =
3046       (pkg_entry != NULL) ? NULL : ClassLoader::package_from_class_name(name());
3047 
3048   Symbol* pkg_name;
3049   if (pkg_entry != NULL) {
3050     pkg_name = pkg_entry->name();
3051   } else {
3052     pkg_name = from_class_name;
3053   }
3054 
3055   if (pkg_name != NULL && loader_data != NULL) {
3056 
3057     // Find in class loader's package entry table.
3058     _package_entry = pkg_entry != NULL ? pkg_entry : loader_data->packages()->lookup_only(pkg_name);
3059 
3060     // If the package name is not found in the loader's package
3061     // entry table, it is an indication that the package has not
3062     // been defined. Consider it defined within the unnamed module.
3063     if (_package_entry == NULL) {
3064 
3065       if (!ModuleEntryTable::javabase_defined()) {
3066         // Before java.base is defined during bootstrapping, define all packages in
3067         // the java.base module.  If a non-java.base package is erroneously placed
3068         // in the java.base module it will be caught later when java.base
3069         // is defined by ModuleEntryTable::verify_javabase_packages check.
3070         assert(ModuleEntryTable::javabase_moduleEntry() != NULL, JAVA_BASE_NAME " module is NULL");
3071         _package_entry = loader_data->packages()->lookup(pkg_name, ModuleEntryTable::javabase_moduleEntry());
3072       } else {
3073         assert(loader_data->unnamed_module() != NULL, "unnamed module is NULL");
3074         _package_entry = loader_data->packages()->lookup(pkg_name,
3075                                                          loader_data->unnamed_module());
3076       }
3077 
3078       // A package should have been successfully created
3079       DEBUG_ONLY(ResourceMark rm(THREAD));
3080       assert(_package_entry != NULL, "Package entry for class %s not found, loader %s",
3081              name()->as_C_string(), loader_data->loader_name_and_id());
3082     }
3083 
3084     if (log_is_enabled(Debug, module)) {
3085       ResourceMark rm(THREAD);
3086       ModuleEntry* m = _package_entry->module();
3087       log_trace(module)("Setting package: class: %s, package: %s, loader: %s, module: %s",
3088                         external_name(),
3089                         pkg_name->as_C_string(),
3090                         loader_data->loader_name_and_id(),
3091                         (m->is_named() ? m->name()->as_C_string() : UNNAMED_MODULE));
3092     }
3093   } else {
3094     ResourceMark rm(THREAD);
3095     log_trace(module)("Setting package: class: %s, package: unnamed, loader: %s, module: %s",
3096                       external_name(),
3097                       (loader_data != NULL) ? loader_data->loader_name_and_id() : "NULL",
3098                       UNNAMED_MODULE);
3099   }
3100 }
3101 
3102 // Function set_classpath_index ensures that for a non-null _package_entry
3103 // of the InstanceKlass, the entry is in the boot loader's package entry table.
3104 // It then sets the classpath_index in the package entry record.
3105 //
3106 // The classpath_index field is used to find the entry on the boot loader class
3107 // path for packages with classes loaded by the boot loader from -Xbootclasspath/a
3108 // in an unnamed module.  It is also used to indicate (for all packages whose
3109 // classes are loaded by the boot loader) that at least one of the package's
3110 // classes has been loaded.
3111 void InstanceKlass::set_classpath_index(s2 path_index) {
3112   if (_package_entry != NULL) {
3113     DEBUG_ONLY(PackageEntryTable* pkg_entry_tbl = ClassLoaderData::the_null_class_loader_data()->packages();)
3114     assert(pkg_entry_tbl->lookup_only(_package_entry->name()) == _package_entry, "Should be same");
3115     assert(path_index != -1, "Unexpected classpath_index");
3116     _package_entry->set_classpath_index(path_index);
3117   }
3118 }
3119 
3120 // different versions of is_same_class_package
3121 
3122 bool InstanceKlass::is_same_class_package(const Klass* class2) const {
3123   oop classloader1 = this->class_loader();
3124   PackageEntry* classpkg1 = this->package();
3125   if (class2->is_objArray_klass()) {
3126     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
3127   }
3128 
3129   oop classloader2;
3130   PackageEntry* classpkg2;
3131   if (class2->is_instance_klass()) {
3132     classloader2 = class2->class_loader();
3133     classpkg2 = class2->package();
3134   } else {
3135     assert(class2->is_typeArray_klass(), "should be type array");
3136     classloader2 = NULL;
3137     classpkg2 = NULL;
3138   }
3139 
3140   // Same package is determined by comparing class loader
3141   // and package entries. Both must be the same. This rule
3142   // applies even to classes that are defined in the unnamed
3143   // package, they still must have the same class loader.
3144   if ((classloader1 == classloader2) && (classpkg1 == classpkg2)) {
3145     return true;
3146   }
3147 
3148   return false;
3149 }
3150 
3151 // return true if this class and other_class are in the same package. Classloader
3152 // and classname information is enough to determine a class's package
3153 bool InstanceKlass::is_same_class_package(oop other_class_loader,
3154                                           const Symbol* other_class_name) const {
3155   if (class_loader() != other_class_loader) {
3156     return false;
3157   }
3158   if (name()->fast_compare(other_class_name) == 0) {
3159      return true;
3160   }
3161 
3162   {
3163     ResourceMark rm;
3164 
3165     bool bad_class_name = false;
3166     TempNewSymbol other_pkg = ClassLoader::package_from_class_name(other_class_name, &bad_class_name);
3167     if (bad_class_name) {
3168       return false;
3169     }
3170     // Check that package_from_class_name() returns NULL, not "", if there is no package.
3171     assert(other_pkg == NULL || other_pkg->utf8_length() > 0, "package name is empty string");
3172 
3173     const Symbol* const this_package_name =
3174       this->package() != NULL ? this->package()->name() : NULL;
3175 
3176     if (this_package_name == NULL || other_pkg == NULL) {
3177       // One of the two doesn't have a package.  Only return true if the other
3178       // one also doesn't have a package.
3179       return this_package_name == other_pkg;
3180     }
3181 
3182     // Check if package is identical
3183     return this_package_name->fast_compare(other_pkg) == 0;
3184   }
3185 }
3186 
3187 static bool is_prohibited_package_slow(Symbol* class_name) {
3188   // Caller has ResourceMark
3189   int length;
3190   jchar* unicode = class_name->as_unicode(length);
3191   return (length >= 5 &&
3192           unicode[0] == 'j' &&
3193           unicode[1] == 'a' &&
3194           unicode[2] == 'v' &&
3195           unicode[3] == 'a' &&
3196           unicode[4] == '/');
3197 }
3198 
3199 // Only boot and platform class loaders can define classes in "java/" packages.
3200 void InstanceKlass::check_prohibited_package(Symbol* class_name,
3201                                              ClassLoaderData* loader_data,
3202                                              TRAPS) {
3203   if (!loader_data->is_boot_class_loader_data() &&
3204       !loader_data->is_platform_class_loader_data() &&
3205       class_name != NULL && class_name->utf8_length() >= 5) {
3206     ResourceMark rm(THREAD);
3207     bool prohibited;
3208     const u1* base = class_name->base();
3209     if ((base[0] | base[1] | base[2] | base[3] | base[4]) & 0x80) {
3210       prohibited = is_prohibited_package_slow(class_name);
3211     } else {
3212       char* name = class_name->as_C_string();
3213       prohibited = (strncmp(name, JAVAPKG, JAVAPKG_LEN) == 0 && name[JAVAPKG_LEN] == '/');
3214     }
3215     if (prohibited) {
3216       TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name);
3217       assert(pkg_name != NULL, "Error in parsing package name starting with 'java/'");
3218       char* name = pkg_name->as_C_string();
3219       const char* class_loader_name = loader_data->loader_name_and_id();
3220       StringUtils::replace_no_expand(name, "/", ".");
3221       const char* msg_text1 = "Class loader (instance of): ";
3222       const char* msg_text2 = " tried to load prohibited package name: ";
3223       size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + strlen(name) + 1;
3224       char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len);
3225       jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, name);
3226       THROW_MSG(vmSymbols::java_lang_SecurityException(), message);
3227     }
3228   }
3229   return;
3230 }
3231 
3232 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3233   constantPoolHandle i_cp(THREAD, constants());
3234   for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3235     int ioff = iter.inner_class_info_index();
3236     if (ioff != 0) {
3237       // Check to see if the name matches the class we're looking for
3238       // before attempting to find the class.
3239       if (i_cp->klass_name_at_matches(this, ioff)) {
3240         Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3241         if (this == inner_klass) {
3242           *ooff = iter.outer_class_info_index();
3243           *noff = iter.inner_name_index();
3244           return true;
3245         }
3246       }
3247     }
3248   }
3249   return false;
3250 }
3251 
3252 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3253   InstanceKlass* outer_klass = NULL;
3254   *inner_is_member = false;
3255   int ooff = 0, noff = 0;
3256   bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3257   if (has_inner_classes_attr) {
3258     constantPoolHandle i_cp(THREAD, constants());
3259     if (ooff != 0) {
3260       Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3261       outer_klass = InstanceKlass::cast(ok);
3262       *inner_is_member = true;
3263     }
3264     if (NULL == outer_klass) {
3265       // It may be a local class; try for that.
3266       int encl_method_class_idx = enclosing_method_class_index();
3267       if (encl_method_class_idx != 0) {
3268         Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
3269         outer_klass = InstanceKlass::cast(ok);
3270         *inner_is_member = false;
3271       }
3272     }
3273   }
3274 
3275   // If no inner class attribute found for this class.
3276   if (NULL == outer_klass) return NULL;
3277 
3278   // Throws an exception if outer klass has not declared k as an inner klass
3279   // We need evidence that each klass knows about the other, or else
3280   // the system could allow a spoof of an inner class to gain access rights.
3281   Reflection::check_for_inner_class(outer_klass, this, *inner_is_member, CHECK_NULL);
3282   return outer_klass;
3283 }
3284 
3285 jint InstanceKlass::compute_modifier_flags() const {
3286   jint access = access_flags().as_int();
3287 
3288   // But check if it happens to be member class.
3289   InnerClassesIterator iter(this);
3290   for (; !iter.done(); iter.next()) {
3291     int ioff = iter.inner_class_info_index();
3292     // Inner class attribute can be zero, skip it.
3293     // Strange but true:  JVM spec. allows null inner class refs.
3294     if (ioff == 0) continue;
3295 
3296     // only look at classes that are already loaded
3297     // since we are looking for the flags for our self.
3298     Symbol* inner_name = constants()->klass_name_at(ioff);
3299     if (name() == inner_name) {
3300       // This is really a member class.
3301       access = iter.inner_access_flags();
3302       break;
3303     }
3304   }
3305   // Remember to strip ACC_SUPER bit
3306   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
3307 }
3308 
3309 jint InstanceKlass::jvmti_class_status() const {
3310   jint result = 0;
3311 
3312   if (is_linked()) {
3313     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3314   }
3315 
3316   if (is_initialized()) {
3317     assert(is_linked(), "Class status is not consistent");
3318     result |= JVMTI_CLASS_STATUS_INITIALIZED;
3319   }
3320   if (is_in_error_state()) {
3321     result |= JVMTI_CLASS_STATUS_ERROR;
3322   }
3323   return result;
3324 }
3325 
3326 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
3327   bool implements_interface; // initialized by method_at_itable_or_null
3328   Method* m = method_at_itable_or_null(holder, index,
3329                                        implements_interface); // out parameter
3330   if (m != NULL) {
3331     assert(implements_interface, "sanity");
3332     return m;
3333   } else if (implements_interface) {
3334     // Throw AbstractMethodError since corresponding itable slot is empty.
3335     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
3336   } else {
3337     // If the interface isn't implemented by the receiver class,
3338     // the VM should throw IncompatibleClassChangeError.
3339     ResourceMark rm(THREAD);
3340     stringStream ss;
3341     bool same_module = (module() == holder->module());
3342     ss.print("Receiver class %s does not implement "
3343              "the interface %s defining the method to be called "
3344              "(%s%s%s)",
3345              external_name(), holder->external_name(),
3346              (same_module) ? joint_in_module_of_loader(holder) : class_in_module_of_loader(),
3347              (same_module) ? "" : "; ",
3348              (same_module) ? "" : holder->class_in_module_of_loader());
3349     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
3350   }
3351 }
3352 
3353 Method* InstanceKlass::method_at_itable_or_null(InstanceKlass* holder, int index, bool& implements_interface) {
3354   klassItable itable(this);
3355   for (int i = 0; i < itable.size_offset_table(); i++) {
3356     itableOffsetEntry* offset_entry = itable.offset_entry(i);
3357     if (offset_entry->interface_klass() == holder) {
3358       implements_interface = true;
3359       itableMethodEntry* ime = offset_entry->first_method_entry(this);
3360       Method* m = ime[index].method();
3361       return m;
3362     }
3363   }
3364   implements_interface = false;
3365   return NULL; // offset entry not found
3366 }
3367 
3368 int InstanceKlass::vtable_index_of_interface_method(Method* intf_method) {
3369   assert(is_linked(), "required");
3370   assert(intf_method->method_holder()->is_interface(), "not an interface method");
3371   assert(is_subtype_of(intf_method->method_holder()), "interface not implemented");
3372 
3373   int vtable_index = Method::invalid_vtable_index;
3374   Symbol* name = intf_method->name();
3375   Symbol* signature = intf_method->signature();
3376 
3377   // First check in default method array
3378   if (!intf_method->is_abstract() && default_methods() != NULL) {
3379     int index = find_method_index(default_methods(),
3380                                   name, signature,
3381                                   Klass::OverpassLookupMode::find,
3382                                   Klass::StaticLookupMode::find,
3383                                   Klass::PrivateLookupMode::find);
3384     if (index >= 0) {
3385       vtable_index = default_vtable_indices()->at(index);
3386     }
3387   }
3388   if (vtable_index == Method::invalid_vtable_index) {
3389     // get vtable_index for miranda methods
3390     klassVtable vt = vtable();
3391     vtable_index = vt.index_of_miranda(name, signature);
3392   }
3393   return vtable_index;
3394 }
3395 
3396 #if INCLUDE_JVMTI
3397 // update default_methods for redefineclasses for methods that are
3398 // not yet in the vtable due to concurrent subclass define and superinterface
3399 // redefinition
3400 // Note: those in the vtable, should have been updated via adjust_method_entries
3401 void InstanceKlass::adjust_default_methods(bool* trace_name_printed) {
3402   // search the default_methods for uses of either obsolete or EMCP methods
3403   if (default_methods() != NULL) {
3404     for (int index = 0; index < default_methods()->length(); index ++) {
3405       Method* old_method = default_methods()->at(index);
3406       if (old_method == NULL || !old_method->is_old()) {
3407         continue; // skip uninteresting entries
3408       }
3409       assert(!old_method->is_deleted(), "default methods may not be deleted");
3410       Method* new_method = old_method->get_new_method();
3411       default_methods()->at_put(index, new_method);
3412 
3413       if (log_is_enabled(Info, redefine, class, update)) {
3414         ResourceMark rm;
3415         if (!(*trace_name_printed)) {
3416           log_info(redefine, class, update)
3417             ("adjust: klassname=%s default methods from name=%s",
3418              external_name(), old_method->method_holder()->external_name());
3419           *trace_name_printed = true;
3420         }
3421         log_debug(redefine, class, update, vtables)
3422           ("default method update: %s(%s) ",
3423            new_method->name()->as_C_string(), new_method->signature()->as_C_string());
3424       }
3425     }
3426   }
3427 }
3428 #endif // INCLUDE_JVMTI
3429 
3430 // On-stack replacement stuff
3431 void InstanceKlass::add_osr_nmethod(nmethod* n) {
3432   assert_lock_strong(CompiledMethod_lock);
3433 #ifndef PRODUCT
3434   nmethod* prev = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), n->comp_level(), true);
3435   assert(prev == NULL || !prev->is_in_use() COMPILER2_PRESENT(|| StressRecompilation),
3436       "redundant OSR recompilation detected. memory leak in CodeCache!");
3437 #endif
3438   // only one compilation can be active
3439   assert(n->is_osr_method(), "wrong kind of nmethod");
3440   n->set_osr_link(osr_nmethods_head());
3441   set_osr_nmethods_head(n);
3442   // Raise the highest osr level if necessary
3443   n->method()->set_highest_osr_comp_level(MAX2(n->method()->highest_osr_comp_level(), n->comp_level()));
3444 
3445   // Get rid of the osr methods for the same bci that have lower levels.
3446   for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
3447     nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
3448     if (inv != NULL && inv->is_in_use()) {
3449       inv->make_not_entrant();
3450     }
3451   }
3452 }
3453 
3454 // Remove osr nmethod from the list. Return true if found and removed.
3455 bool InstanceKlass::remove_osr_nmethod(nmethod* n) {
3456   // This is a short non-blocking critical region, so the no safepoint check is ok.
3457   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock
3458                  , Mutex::_no_safepoint_check_flag);
3459   assert(n->is_osr_method(), "wrong kind of nmethod");
3460   nmethod* last = NULL;
3461   nmethod* cur  = osr_nmethods_head();
3462   int max_level = CompLevel_none;  // Find the max comp level excluding n
3463   Method* m = n->method();
3464   // Search for match
3465   bool found = false;
3466   while(cur != NULL && cur != n) {
3467     if (m == cur->method()) {
3468       // Find max level before n
3469       max_level = MAX2(max_level, cur->comp_level());
3470     }
3471     last = cur;
3472     cur = cur->osr_link();
3473   }
3474   nmethod* next = NULL;
3475   if (cur == n) {
3476     found = true;
3477     next = cur->osr_link();
3478     if (last == NULL) {
3479       // Remove first element
3480       set_osr_nmethods_head(next);
3481     } else {
3482       last->set_osr_link(next);
3483     }
3484   }
3485   n->set_osr_link(NULL);
3486   cur = next;
3487   while (cur != NULL) {
3488     // Find max level after n
3489     if (m == cur->method()) {
3490       max_level = MAX2(max_level, cur->comp_level());
3491     }
3492     cur = cur->osr_link();
3493   }
3494   m->set_highest_osr_comp_level(max_level);
3495   return found;
3496 }
3497 
3498 int InstanceKlass::mark_osr_nmethods(const Method* m) {
3499   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock,
3500                  Mutex::_no_safepoint_check_flag);
3501   nmethod* osr = osr_nmethods_head();
3502   int found = 0;
3503   while (osr != NULL) {
3504     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3505     if (osr->method() == m) {
3506       osr->mark_for_deoptimization();
3507       found++;
3508     }
3509     osr = osr->osr_link();
3510   }
3511   return found;
3512 }
3513 
3514 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
3515   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock,
3516                  Mutex::_no_safepoint_check_flag);
3517   nmethod* osr = osr_nmethods_head();
3518   nmethod* best = NULL;
3519   while (osr != NULL) {
3520     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3521     // There can be a time when a c1 osr method exists but we are waiting
3522     // for a c2 version. When c2 completes its osr nmethod we will trash
3523     // the c1 version and only be able to find the c2 version. However
3524     // while we overflow in the c1 code at back branches we don't want to
3525     // try and switch to the same code as we are already running
3526 
3527     if (osr->method() == m &&
3528         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
3529       if (match_level) {
3530         if (osr->comp_level() == comp_level) {
3531           // Found a match - return it.
3532           return osr;
3533         }
3534       } else {
3535         if (best == NULL || (osr->comp_level() > best->comp_level())) {
3536           if (osr->comp_level() == CompilationPolicy::highest_compile_level()) {
3537             // Found the best possible - return it.
3538             return osr;
3539           }
3540           best = osr;
3541         }
3542       }
3543     }
3544     osr = osr->osr_link();
3545   }
3546 
3547   assert(match_level == false || best == NULL, "shouldn't pick up anything if match_level is set");
3548   if (best != NULL && best->comp_level() >= comp_level) {
3549     return best;
3550   }
3551   return NULL;
3552 }
3553 
3554 // -----------------------------------------------------------------------------------------------------
3555 // Printing
3556 
3557 #define BULLET  " - "
3558 
3559 static const char* state_names[] = {
3560   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3561 };
3562 
3563 static void print_vtable(address self, intptr_t* start, int len, outputStream* st) {
3564   ResourceMark rm;
3565   int* forward_refs = NEW_RESOURCE_ARRAY(int, len);
3566   for (int i = 0; i < len; i++)  forward_refs[i] = 0;
3567   for (int i = 0; i < len; i++) {
3568     intptr_t e = start[i];
3569     st->print("%d : " INTPTR_FORMAT, i, e);
3570     if (forward_refs[i] != 0) {
3571       int from = forward_refs[i];
3572       int off = (int) start[from];
3573       st->print(" (offset %d <= [%d])", off, from);
3574     }
3575     if (MetaspaceObj::is_valid((Metadata*)e)) {
3576       st->print(" ");
3577       ((Metadata*)e)->print_value_on(st);
3578     } else if (self != NULL && e > 0 && e < 0x10000) {
3579       address location = self + e;
3580       int index = (int)((intptr_t*)location - start);
3581       st->print(" (offset %d => [%d])", (int)e, index);
3582       if (index >= 0 && index < len)
3583         forward_refs[index] = i;
3584     }
3585     st->cr();
3586   }
3587 }
3588 
3589 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3590   return print_vtable(NULL, reinterpret_cast<intptr_t*>(start), len, st);
3591 }
3592 
3593 template<typename T>
3594  static void print_array_on(outputStream* st, Array<T>* array) {
3595    if (array == NULL) { st->print_cr("NULL"); return; }
3596    array->print_value_on(st); st->cr();
3597    if (Verbose || WizardMode) {
3598      for (int i = 0; i < array->length(); i++) {
3599        st->print("%d : ", i); array->at(i)->print_value_on(st); st->cr();
3600      }
3601    }
3602  }
3603 
3604 static void print_array_on(outputStream* st, Array<int>* array) {
3605   if (array == NULL) { st->print_cr("NULL"); return; }
3606   array->print_value_on(st); st->cr();
3607   if (Verbose || WizardMode) {
3608     for (int i = 0; i < array->length(); i++) {
3609       st->print("%d : %d", i, array->at(i)); st->cr();
3610     }
3611   }
3612 }
3613 
3614 void InstanceKlass::print_on(outputStream* st) const {
3615   assert(is_klass(), "must be klass");
3616   Klass::print_on(st);
3617 
3618   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3619   st->print(BULLET"klass size:        %d", size());                               st->cr();
3620   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
3621   st->print(BULLET"misc flags:        0x%x", _misc_flags);                        st->cr();
3622   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
3623   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3624   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3625   st->print(BULLET"sub:               ");
3626   Klass* sub = subklass();
3627   int n;
3628   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
3629     if (n < MaxSubklassPrintSize) {
3630       sub->print_value_on(st);
3631       st->print("   ");
3632     }
3633   }
3634   if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize);
3635   st->cr();
3636 
3637   if (is_interface()) {
3638     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
3639     if (nof_implementors() == 1) {
3640       st->print_cr(BULLET"implementor:    ");
3641       st->print("   ");
3642       implementor()->print_value_on(st);
3643       st->cr();
3644     }
3645   }
3646 
3647   st->print(BULLET"arrays:            "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3648   st->print(BULLET"methods:           "); print_array_on(st, methods());
3649   st->print(BULLET"method ordering:   "); print_array_on(st, method_ordering());
3650   st->print(BULLET"default_methods:   "); print_array_on(st, default_methods());












3651   if (default_vtable_indices() != NULL) {
3652     st->print(BULLET"default vtable indices:   "); print_array_on(st, default_vtable_indices());
3653   }
3654   st->print(BULLET"local interfaces:  "); print_array_on(st, local_interfaces());
3655   st->print(BULLET"trans. interfaces: "); print_array_on(st, transitive_interfaces());
3656   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
3657   if (class_loader_data() != NULL) {
3658     st->print(BULLET"class loader data:  ");
3659     class_loader_data()->print_value_on(st);
3660     st->cr();
3661   }
3662   if (source_file_name() != NULL) {
3663     st->print(BULLET"source file:       ");
3664     source_file_name()->print_value_on(st);
3665     st->cr();
3666   }
3667   if (source_debug_extension() != NULL) {
3668     st->print(BULLET"source debug extension:       ");
3669     st->print("%s", source_debug_extension());
3670     st->cr();
3671   }
3672   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
3673   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
3674   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
3675   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
3676   {
3677     bool have_pv = false;
3678     // previous versions are linked together through the InstanceKlass
3679     for (InstanceKlass* pv_node = previous_versions();
3680          pv_node != NULL;
3681          pv_node = pv_node->previous_versions()) {
3682       if (!have_pv)
3683         st->print(BULLET"previous version:  ");
3684       have_pv = true;
3685       pv_node->constants()->print_value_on(st);
3686     }
3687     if (have_pv) st->cr();
3688   }
3689 
3690   if (generic_signature() != NULL) {
3691     st->print(BULLET"generic signature: ");
3692     generic_signature()->print_value_on(st);
3693     st->cr();
3694   }
3695   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
3696   st->print(BULLET"nest members:     "); nest_members()->print_value_on(st);     st->cr();
3697   if (record_components() != NULL) {
3698     st->print(BULLET"record components:     "); record_components()->print_value_on(st);     st->cr();
3699   }
3700   st->print(BULLET"permitted subclasses:     "); permitted_subclasses()->print_value_on(st);     st->cr();
3701   if (java_mirror() != NULL) {
3702     st->print(BULLET"java mirror:       ");
3703     java_mirror()->print_value_on(st);
3704     st->cr();
3705   } else {
3706     st->print_cr(BULLET"java mirror:       NULL");
3707   }
3708   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3709   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
3710   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3711   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(NULL, start_of_itable(), itable_length(), st);
3712   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3713   FieldPrinter print_static_field(st);
3714   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3715   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3716   FieldPrinter print_nonstatic_field(st);
3717   InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3718   ik->print_nonstatic_fields(&print_nonstatic_field);
3719 
3720   st->print(BULLET"non-static oop maps: ");
3721   OopMapBlock* map     = start_of_nonstatic_oop_maps();
3722   OopMapBlock* end_map = map + nonstatic_oop_map_count();
3723   while (map < end_map) {
3724     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3725     map++;
3726   }
3727   st->cr();
3728 }
3729 
3730 void InstanceKlass::print_value_on(outputStream* st) const {
3731   assert(is_klass(), "must be klass");
3732   if (Verbose || WizardMode)  access_flags().print_on(st);
3733   name()->print_value_on(st);
3734 }
3735 
3736 void FieldPrinter::do_field(fieldDescriptor* fd) {
3737   _st->print(BULLET);
3738    if (_obj == NULL) {
3739      fd->print_on(_st);
3740      _st->cr();
3741    } else {
3742      fd->print_on_for(_st, _obj);
3743      _st->cr();
3744    }
3745 }
3746 
3747 
3748 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3749   Klass::oop_print_on(obj, st);
3750 
3751   if (this == vmClasses::String_klass()) {
3752     typeArrayOop value  = java_lang_String::value(obj);
3753     juint        length = java_lang_String::length(obj);
3754     if (value != NULL &&
3755         value->is_typeArray() &&
3756         length <= (juint) value->length()) {
3757       st->print(BULLET"string: ");
3758       java_lang_String::print(obj, st);
3759       st->cr();
3760     }
3761   }
3762 
3763   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
3764   FieldPrinter print_field(st, obj);
3765   print_nonstatic_fields(&print_field);
3766 
3767   if (this == vmClasses::Class_klass()) {
3768     st->print(BULLET"signature: ");
3769     java_lang_Class::print_signature(obj, st);
3770     st->cr();
3771     Klass* real_klass = java_lang_Class::as_Klass(obj);
3772     if (real_klass != NULL && real_klass->is_instance_klass()) {
3773       st->print_cr(BULLET"---- static fields (%d words):", java_lang_Class::static_oop_field_count(obj));
3774       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3775     }
3776   } else if (this == vmClasses::MethodType_klass()) {
3777     st->print(BULLET"signature: ");
3778     java_lang_invoke_MethodType::print_signature(obj, st);
3779     st->cr();
3780   }
3781 }
3782 
3783 #ifndef PRODUCT
3784 
3785 bool InstanceKlass::verify_itable_index(int i) {
3786   int method_count = klassItable::method_count_for_interface(this);
3787   assert(i >= 0 && i < method_count, "index out of bounds");
3788   return true;
3789 }
3790 
3791 #endif //PRODUCT
3792 
3793 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
3794   st->print("a ");
3795   name()->print_value_on(st);
3796   obj->print_address_on(st);
3797   if (this == vmClasses::String_klass()
3798       && java_lang_String::value(obj) != NULL) {
3799     ResourceMark rm;
3800     int len = java_lang_String::length(obj);
3801     int plen = (len < 24 ? len : 12);
3802     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
3803     st->print(" = \"%s\"", str);
3804     if (len > plen)
3805       st->print("...[%d]", len);
3806   } else if (this == vmClasses::Class_klass()) {
3807     Klass* k = java_lang_Class::as_Klass(obj);
3808     st->print(" = ");
3809     if (k != NULL) {
3810       k->print_value_on(st);
3811     } else {
3812       const char* tname = type2name(java_lang_Class::primitive_type(obj));
3813       st->print("%s", tname ? tname : "type?");
3814     }
3815   } else if (this == vmClasses::MethodType_klass()) {
3816     st->print(" = ");
3817     java_lang_invoke_MethodType::print_signature(obj, st);
3818   } else if (java_lang_boxing_object::is_instance(obj)) {
3819     st->print(" = ");
3820     java_lang_boxing_object::print(obj, st);
3821   } else if (this == vmClasses::LambdaForm_klass()) {
3822     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
3823     if (vmentry != NULL) {
3824       st->print(" => ");
3825       vmentry->print_value_on(st);
3826     }
3827   } else if (this == vmClasses::MemberName_klass()) {
3828     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
3829     if (vmtarget != NULL) {
3830       st->print(" = ");
3831       vmtarget->print_value_on(st);
3832     } else {
3833       oop clazz = java_lang_invoke_MemberName::clazz(obj);
3834       oop name  = java_lang_invoke_MemberName::name(obj);
3835       if (clazz != NULL) {
3836         clazz->print_value_on(st);
3837       } else {
3838         st->print("NULL");
3839       }
3840       st->print(".");
3841       if (name != NULL) {
3842         name->print_value_on(st);
3843       } else {
3844         st->print("NULL");
3845       }
3846     }
3847   }
3848 }
3849 
3850 const char* InstanceKlass::internal_name() const {
3851   return external_name();
3852 }
3853 
3854 void InstanceKlass::print_class_load_logging(ClassLoaderData* loader_data,
3855                                              const ModuleEntry* module_entry,
3856                                              const ClassFileStream* cfs) const {
3857   if (ClassListWriter::is_enabled()) {
3858     ClassListWriter::write(this, cfs);
3859   }
3860 
3861   if (!log_is_enabled(Info, class, load)) {
3862     return;
3863   }
3864 
3865   ResourceMark rm;
3866   LogMessage(class, load) msg;
3867   stringStream info_stream;
3868 
3869   // Name and class hierarchy info
3870   info_stream.print("%s", external_name());
3871 
3872   // Source
3873   if (cfs != NULL) {
3874     if (cfs->source() != NULL) {
3875       const char* module_name = (module_entry->name() == NULL) ? UNNAMED_MODULE : module_entry->name()->as_C_string();
3876       if (module_name != NULL) {
3877         // When the boot loader created the stream, it didn't know the module name
3878         // yet. Let's format it now.
3879         if (cfs->from_boot_loader_modules_image()) {
3880           info_stream.print(" source: jrt:/%s", module_name);
3881         } else {
3882           info_stream.print(" source: %s", cfs->source());
3883         }
3884       } else {
3885         info_stream.print(" source: %s", cfs->source());
3886       }
3887     } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) {
3888       Thread* current = Thread::current();
3889       Klass* caller = current->is_Java_thread() ?
3890         JavaThread::cast(current)->security_get_caller_class(1):
3891         NULL;
3892       // caller can be NULL, for example, during a JVMTI VM_Init hook
3893       if (caller != NULL) {
3894         info_stream.print(" source: instance of %s", caller->external_name());
3895       } else {
3896         // source is unknown
3897       }
3898     } else {
3899       oop class_loader = loader_data->class_loader();
3900       info_stream.print(" source: %s", class_loader->klass()->external_name());
3901     }
3902   } else {
3903     assert(this->is_shared(), "must be");
3904     if (MetaspaceShared::is_shared_dynamic((void*)this)) {
3905       info_stream.print(" source: shared objects file (top)");
3906     } else {
3907       info_stream.print(" source: shared objects file");
3908     }
3909   }
3910 
3911   msg.info("%s", info_stream.as_string());
3912 
3913   if (log_is_enabled(Debug, class, load)) {
3914     stringStream debug_stream;
3915 
3916     // Class hierarchy info
3917     debug_stream.print(" klass: " INTPTR_FORMAT " super: " INTPTR_FORMAT,
3918                        p2i(this),  p2i(superklass()));
3919 
3920     // Interfaces
3921     if (local_interfaces() != NULL && local_interfaces()->length() > 0) {
3922       debug_stream.print(" interfaces:");
3923       int length = local_interfaces()->length();
3924       for (int i = 0; i < length; i++) {
3925         debug_stream.print(" " INTPTR_FORMAT,
3926                            p2i(InstanceKlass::cast(local_interfaces()->at(i))));
3927       }
3928     }
3929 
3930     // Class loader
3931     debug_stream.print(" loader: [");
3932     loader_data->print_value_on(&debug_stream);
3933     debug_stream.print("]");
3934 
3935     // Classfile checksum
3936     if (cfs) {
3937       debug_stream.print(" bytes: %d checksum: %08x",
3938                          cfs->length(),
3939                          ClassLoader::crc32(0, (const char*)cfs->buffer(),
3940                          cfs->length()));
3941     }
3942 
3943     msg.debug("%s", debug_stream.as_string());
3944   }
3945 }
3946 
3947 // Verification
3948 
3949 class VerifyFieldClosure: public BasicOopIterateClosure {
3950  protected:
3951   template <class T> void do_oop_work(T* p) {
3952     oop obj = RawAccess<>::oop_load(p);
3953     if (!oopDesc::is_oop_or_null(obj)) {
3954       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj));
3955       Universe::print_on(tty);
3956       guarantee(false, "boom");
3957     }
3958   }
3959  public:
3960   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
3961   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
3962 };
3963 
3964 void InstanceKlass::verify_on(outputStream* st) {
3965 #ifndef PRODUCT
3966   // Avoid redundant verifies, this really should be in product.
3967   if (_verify_count == Universe::verify_count()) return;
3968   _verify_count = Universe::verify_count();
3969 #endif
3970 
3971   // Verify Klass
3972   Klass::verify_on(st);
3973 
3974   // Verify that klass is present in ClassLoaderData
3975   guarantee(class_loader_data()->contains_klass(this),
3976             "this class isn't found in class loader data");
3977 
3978   // Verify vtables
3979   if (is_linked()) {
3980     // $$$ This used to be done only for m/s collections.  Doing it
3981     // always seemed a valid generalization.  (DLD -- 6/00)
3982     vtable().verify(st);
3983   }
3984 
3985   // Verify first subklass
3986   if (subklass() != NULL) {
3987     guarantee(subklass()->is_klass(), "should be klass");
3988   }
3989 
3990   // Verify siblings
3991   Klass* super = this->super();
3992   Klass* sib = next_sibling();
3993   if (sib != NULL) {
3994     if (sib == this) {
3995       fatal("subclass points to itself " PTR_FORMAT, p2i(sib));
3996     }
3997 
3998     guarantee(sib->is_klass(), "should be klass");
3999     guarantee(sib->super() == super, "siblings should have same superklass");
4000   }
4001 
4002   // Verify local interfaces
4003   if (local_interfaces()) {
4004     Array<InstanceKlass*>* local_interfaces = this->local_interfaces();
4005     for (int j = 0; j < local_interfaces->length(); j++) {
4006       InstanceKlass* e = local_interfaces->at(j);
4007       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
4008     }
4009   }
4010 
4011   // Verify transitive interfaces
4012   if (transitive_interfaces() != NULL) {
4013     Array<InstanceKlass*>* transitive_interfaces = this->transitive_interfaces();
4014     for (int j = 0; j < transitive_interfaces->length(); j++) {
4015       InstanceKlass* e = transitive_interfaces->at(j);
4016       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
4017     }
4018   }
4019 
4020   // Verify methods
4021   if (methods() != NULL) {
4022     Array<Method*>* methods = this->methods();
4023     for (int j = 0; j < methods->length(); j++) {
4024       guarantee(methods->at(j)->is_method(), "non-method in methods array");
4025     }
4026     for (int j = 0; j < methods->length() - 1; j++) {
4027       Method* m1 = methods->at(j);
4028       Method* m2 = methods->at(j + 1);
4029       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
4030     }
4031   }
4032 
4033   // Verify method ordering
4034   if (method_ordering() != NULL) {
4035     Array<int>* method_ordering = this->method_ordering();
4036     int length = method_ordering->length();
4037     if (JvmtiExport::can_maintain_original_method_order() ||
4038         ((UseSharedSpaces || Arguments::is_dumping_archive()) && length != 0)) {
4039       guarantee(length == methods()->length(), "invalid method ordering length");
4040       jlong sum = 0;
4041       for (int j = 0; j < length; j++) {
4042         int original_index = method_ordering->at(j);
4043         guarantee(original_index >= 0, "invalid method ordering index");
4044         guarantee(original_index < length, "invalid method ordering index");
4045         sum += original_index;
4046       }
4047       // Verify sum of indices 0,1,...,length-1
4048       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
4049     } else {
4050       guarantee(length == 0, "invalid method ordering length");
4051     }
4052   }
4053 
4054   // Verify default methods
4055   if (default_methods() != NULL) {
4056     Array<Method*>* methods = this->default_methods();
4057     for (int j = 0; j < methods->length(); j++) {
4058       guarantee(methods->at(j)->is_method(), "non-method in methods array");
4059     }
4060     for (int j = 0; j < methods->length() - 1; j++) {
4061       Method* m1 = methods->at(j);
4062       Method* m2 = methods->at(j + 1);
4063       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
4064     }
4065   }
4066 
4067   // Verify JNI static field identifiers
4068   if (jni_ids() != NULL) {
4069     jni_ids()->verify(this);
4070   }
4071 
4072   // Verify other fields
4073   if (constants() != NULL) {
4074     guarantee(constants()->is_constantPool(), "should be constant pool");
4075   }
4076 }
4077 
4078 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
4079   Klass::oop_verify_on(obj, st);
4080   VerifyFieldClosure blk;
4081   obj->oop_iterate(&blk);
4082 }
4083 
4084 
4085 // JNIid class for jfieldIDs only
4086 // Note to reviewers:
4087 // These JNI functions are just moved over to column 1 and not changed
4088 // in the compressed oops workspace.
4089 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
4090   _holder = holder;
4091   _offset = offset;
4092   _next = next;
4093   debug_only(_is_static_field_id = false;)
4094 }
4095 
4096 
4097 JNIid* JNIid::find(int offset) {
4098   JNIid* current = this;
4099   while (current != NULL) {
4100     if (current->offset() == offset) return current;
4101     current = current->next();
4102   }
4103   return NULL;
4104 }
4105 
4106 void JNIid::deallocate(JNIid* current) {
4107   while (current != NULL) {
4108     JNIid* next = current->next();
4109     delete current;
4110     current = next;
4111   }
4112 }
4113 
4114 
4115 void JNIid::verify(Klass* holder) {
4116   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
4117   int end_field_offset;
4118   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
4119 
4120   JNIid* current = this;
4121   while (current != NULL) {
4122     guarantee(current->holder() == holder, "Invalid klass in JNIid");
4123 #ifdef ASSERT
4124     int o = current->offset();
4125     if (current->is_static_field_id()) {
4126       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
4127     }
4128 #endif
4129     current = current->next();
4130   }
4131 }
4132 
4133 void InstanceKlass::set_init_state(ClassState state) {
4134 #ifdef ASSERT
4135   bool good_state = is_shared() ? (_init_state <= state)
4136                                                : (_init_state < state);
4137   assert(good_state || state == allocated, "illegal state transition");
4138 #endif
4139   assert(_init_thread == NULL, "should be cleared before state change");
4140   _init_state = (u1)state;
4141 }
4142 
4143 #if INCLUDE_JVMTI
4144 
4145 // RedefineClasses() support for previous versions
4146 
4147 // Globally, there is at least one previous version of a class to walk
4148 // during class unloading, which is saved because old methods in the class
4149 // are still running.   Otherwise the previous version list is cleaned up.
4150 bool InstanceKlass::_has_previous_versions = false;
4151 
4152 // Returns true if there are previous versions of a class for class
4153 // unloading only. Also resets the flag to false. purge_previous_version
4154 // will set the flag to true if there are any left, i.e., if there's any
4155 // work to do for next time. This is to avoid the expensive code cache
4156 // walk in CLDG::clean_deallocate_lists().
4157 bool InstanceKlass::has_previous_versions_and_reset() {
4158   bool ret = _has_previous_versions;
4159   log_trace(redefine, class, iklass, purge)("Class unloading: has_previous_versions = %s",
4160      ret ? "true" : "false");
4161   _has_previous_versions = false;
4162   return ret;
4163 }
4164 
4165 // Purge previous versions before adding new previous versions of the class and
4166 // during class unloading.
4167 void InstanceKlass::purge_previous_version_list() {
4168   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
4169   assert(has_been_redefined(), "Should only be called for main class");
4170 
4171   // Quick exit.
4172   if (previous_versions() == NULL) {
4173     return;
4174   }
4175 
4176   // This klass has previous versions so see what we can cleanup
4177   // while it is safe to do so.
4178 
4179   int deleted_count = 0;    // leave debugging breadcrumbs
4180   int live_count = 0;
4181   ClassLoaderData* loader_data = class_loader_data();
4182   assert(loader_data != NULL, "should never be null");
4183 
4184   ResourceMark rm;
4185   log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name());
4186 
4187   // previous versions are linked together through the InstanceKlass
4188   InstanceKlass* pv_node = previous_versions();
4189   InstanceKlass* last = this;
4190   int version = 0;
4191 
4192   // check the previous versions list
4193   for (; pv_node != NULL; ) {
4194 
4195     ConstantPool* pvcp = pv_node->constants();
4196     assert(pvcp != NULL, "cp ref was unexpectedly cleared");
4197 
4198     if (!pvcp->on_stack()) {
4199       // If the constant pool isn't on stack, none of the methods
4200       // are executing.  Unlink this previous_version.
4201       // The previous version InstanceKlass is on the ClassLoaderData deallocate list
4202       // so will be deallocated during the next phase of class unloading.
4203       log_trace(redefine, class, iklass, purge)
4204         ("previous version " INTPTR_FORMAT " is dead.", p2i(pv_node));
4205       // For debugging purposes.
4206       pv_node->set_is_scratch_class();
4207       // Unlink from previous version list.
4208       assert(pv_node->class_loader_data() == loader_data, "wrong loader_data");
4209       InstanceKlass* next = pv_node->previous_versions();
4210       pv_node->link_previous_versions(NULL);   // point next to NULL
4211       last->link_previous_versions(next);
4212       // Delete this node directly. Nothing is referring to it and we don't
4213       // want it to increase the counter for metadata to delete in CLDG.
4214       MetadataFactory::free_metadata(loader_data, pv_node);
4215       pv_node = next;
4216       deleted_count++;
4217       version++;
4218       continue;
4219     } else {
4220       log_trace(redefine, class, iklass, purge)("previous version " INTPTR_FORMAT " is alive", p2i(pv_node));
4221       assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
4222       guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
4223       live_count++;
4224       // found a previous version for next time we do class unloading
4225       _has_previous_versions = true;
4226     }
4227 
4228     // next previous version
4229     last = pv_node;
4230     pv_node = pv_node->previous_versions();
4231     version++;
4232   }
4233   log_trace(redefine, class, iklass, purge)
4234     ("previous version stats: live=%d, deleted=%d", live_count, deleted_count);
4235 }
4236 
4237 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,
4238                                                 int emcp_method_count) {
4239   int obsolete_method_count = old_methods->length() - emcp_method_count;
4240 
4241   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
4242       _previous_versions != NULL) {
4243     // We have a mix of obsolete and EMCP methods so we have to
4244     // clear out any matching EMCP method entries the hard way.
4245     int local_count = 0;
4246     for (int i = 0; i < old_methods->length(); i++) {
4247       Method* old_method = old_methods->at(i);
4248       if (old_method->is_obsolete()) {
4249         // only obsolete methods are interesting
4250         Symbol* m_name = old_method->name();
4251         Symbol* m_signature = old_method->signature();
4252 
4253         // previous versions are linked together through the InstanceKlass
4254         int j = 0;
4255         for (InstanceKlass* prev_version = _previous_versions;
4256              prev_version != NULL;
4257              prev_version = prev_version->previous_versions(), j++) {
4258 
4259           Array<Method*>* method_refs = prev_version->methods();
4260           for (int k = 0; k < method_refs->length(); k++) {
4261             Method* method = method_refs->at(k);
4262 
4263             if (!method->is_obsolete() &&
4264                 method->name() == m_name &&
4265                 method->signature() == m_signature) {
4266               // The current RedefineClasses() call has made all EMCP
4267               // versions of this method obsolete so mark it as obsolete
4268               log_trace(redefine, class, iklass, add)
4269                 ("%s(%s): flush obsolete method @%d in version @%d",
4270                  m_name->as_C_string(), m_signature->as_C_string(), k, j);
4271 
4272               method->set_is_obsolete();
4273               break;
4274             }
4275           }
4276 
4277           // The previous loop may not find a matching EMCP method, but
4278           // that doesn't mean that we can optimize and not go any
4279           // further back in the PreviousVersion generations. The EMCP
4280           // method for this generation could have already been made obsolete,
4281           // but there still may be an older EMCP method that has not
4282           // been made obsolete.
4283         }
4284 
4285         if (++local_count >= obsolete_method_count) {
4286           // no more obsolete methods so bail out now
4287           break;
4288         }
4289       }
4290     }
4291   }
4292 }
4293 
4294 // Save the scratch_class as the previous version if any of the methods are running.
4295 // The previous_versions are used to set breakpoints in EMCP methods and they are
4296 // also used to clean MethodData links to redefined methods that are no longer running.
4297 void InstanceKlass::add_previous_version(InstanceKlass* scratch_class,
4298                                          int emcp_method_count) {
4299   assert(Thread::current()->is_VM_thread(),
4300          "only VMThread can add previous versions");
4301 
4302   ResourceMark rm;
4303   log_trace(redefine, class, iklass, add)
4304     ("adding previous version ref for %s, EMCP_cnt=%d", scratch_class->external_name(), emcp_method_count);
4305 
4306   // Clean out old previous versions for this class
4307   purge_previous_version_list();
4308 
4309   // Mark newly obsolete methods in remaining previous versions.  An EMCP method from
4310   // a previous redefinition may be made obsolete by this redefinition.
4311   Array<Method*>* old_methods = scratch_class->methods();
4312   mark_newly_obsolete_methods(old_methods, emcp_method_count);
4313 
4314   // If the constant pool for this previous version of the class
4315   // is not marked as being on the stack, then none of the methods
4316   // in this previous version of the class are on the stack so
4317   // we don't need to add this as a previous version.
4318   ConstantPool* cp_ref = scratch_class->constants();
4319   if (!cp_ref->on_stack()) {
4320     log_trace(redefine, class, iklass, add)("scratch class not added; no methods are running");
4321     // For debugging purposes.
4322     scratch_class->set_is_scratch_class();
4323     scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class);
4324     return;
4325   }
4326 
4327   // Add previous version if any methods are still running.
4328   // Set has_previous_version flag for processing during class unloading.
4329   _has_previous_versions = true;
4330   log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack.");
4331   assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");
4332   scratch_class->link_previous_versions(previous_versions());
4333   link_previous_versions(scratch_class);
4334 } // end add_previous_version()
4335 
4336 #endif // INCLUDE_JVMTI
4337 
4338 Method* InstanceKlass::method_with_idnum(int idnum) {
4339   Method* m = NULL;
4340   if (idnum < methods()->length()) {
4341     m = methods()->at(idnum);
4342   }
4343   if (m == NULL || m->method_idnum() != idnum) {
4344     for (int index = 0; index < methods()->length(); ++index) {
4345       m = methods()->at(index);
4346       if (m->method_idnum() == idnum) {
4347         return m;
4348       }
4349     }
4350     // None found, return null for the caller to handle.
4351     return NULL;
4352   }
4353   return m;
4354 }
4355 
4356 
4357 Method* InstanceKlass::method_with_orig_idnum(int idnum) {
4358   if (idnum >= methods()->length()) {
4359     return NULL;
4360   }
4361   Method* m = methods()->at(idnum);
4362   if (m != NULL && m->orig_method_idnum() == idnum) {
4363     return m;
4364   }
4365   // Obsolete method idnum does not match the original idnum
4366   for (int index = 0; index < methods()->length(); ++index) {
4367     m = methods()->at(index);
4368     if (m->orig_method_idnum() == idnum) {
4369       return m;
4370     }
4371   }
4372   // None found, return null for the caller to handle.
4373   return NULL;
4374 }
4375 
4376 
4377 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {
4378   InstanceKlass* holder = get_klass_version(version);
4379   if (holder == NULL) {
4380     return NULL; // The version of klass is gone, no method is found
4381   }
4382   Method* method = holder->method_with_orig_idnum(idnum);
4383   return method;
4384 }
4385 
4386 #if INCLUDE_JVMTI
4387 JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() {
4388   return _cached_class_file;
4389 }
4390 
4391 jint InstanceKlass::get_cached_class_file_len() {
4392   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
4393 }
4394 
4395 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
4396   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
4397 }
4398 #endif
4399 
4400 // Make a step iterating over the class hierarchy under the root class.
4401 // Skips subclasses if requested.
4402 void ClassHierarchyIterator::next() {
4403   assert(_current != NULL, "required");
4404   if (_visit_subclasses && _current->subklass() != NULL) {
4405     _current = _current->subklass();
4406     return; // visit next subclass
4407   }
4408   _visit_subclasses = true; // reset
4409   while (_current->next_sibling() == NULL && _current != _root) {
4410     _current = _current->superklass(); // backtrack; no more sibling subclasses left
4411   }
4412   if (_current == _root) {
4413     // Iteration is over (back at root after backtracking). Invalidate the iterator.
4414     _current = NULL;
4415     return;
4416   }
4417   _current = _current->next_sibling();
4418   return; // visit next sibling subclass
4419 }
--- EOF ---