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