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