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