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