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