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(ArrayStorageProperties storage_props, bool or_null, int n, TRAPS) {
1402   assert(!storage_props.is_flattened(), "Can't be flattened");
1403   // Need load-acquire for lock-free read
1404   if (array_klasses_acquire() == NULL) {
1405     if (or_null) return NULL;
1406 
1407     ResourceMark rm;
1408     JavaThread *jt = (JavaThread *)THREAD;
1409     {
1410       // Atomic creation of array_klasses
1411       MutexLocker ma(MultiArray_lock, THREAD);
1412 
1413       // Check if update has already taken place
1414       if (array_klasses() == NULL) {
1415         Klass*    k = ObjArrayKlass::allocate_objArray_klass(storage_props, 1, this, CHECK_NULL);
1416         // use 'release' to pair with lock-free load
1417         release_set_array_klasses(k);
1418       }
1419     }
1420   }
1421   // _this will always be set at this point
1422   ObjArrayKlass* oak = (ObjArrayKlass*)array_klasses();
1423   if (or_null) {
1424     return oak->array_klass_or_null(storage_props, n);
1425   }
1426   return oak->array_klass(storage_props, n, THREAD);
1427 }
1428 
1429 Klass* InstanceKlass::array_klass_impl(ArrayStorageProperties storage_props, bool or_null, TRAPS) {
1430   return array_klass_impl(storage_props, or_null, 1, THREAD);
1431 }
1432 
1433 static int call_class_initializer_counter = 0;   // for debugging
1434 
1435 Method* InstanceKlass::class_initializer() const {
1436   Method* clinit = find_method(
1437       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1438   if (clinit != NULL && clinit->has_valid_initializer_flags()) {
1439     return clinit;
1440   }
1441   return NULL;
1442 }
1443 
1444 void InstanceKlass::call_class_initializer(TRAPS) {
1445   if (ReplayCompiles &&
1446       (ReplaySuppressInitializers == 1 ||
1447        (ReplaySuppressInitializers >= 2 && class_loader() != NULL))) {
1448     // Hide the existence of the initializer for the purpose of replaying the compile
1449     return;
1450   }
1451 
1452   methodHandle h_method(THREAD, class_initializer());
1453   assert(!is_initialized(), "we cannot initialize twice");
1454   LogTarget(Info, class, init) lt;
1455   if (lt.is_enabled()) {
1456     ResourceMark rm;
1457     LogStream ls(lt);
1458     ls.print("%d Initializing ", call_class_initializer_counter++);
1459     name()->print_value_on(&ls);
1460     ls.print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", p2i(this));
1461   }
1462   if (h_method() != NULL) {
1463     JavaCallArguments args; // No arguments
1464     JavaValue result(T_VOID);
1465     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1466   }
1467 }
1468 
1469 
1470 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1471   InterpreterOopMap* entry_for) {
1472   // Lazily create the _oop_map_cache at first request
1473   // Lock-free access requires load_acquire.
1474   OopMapCache* oop_map_cache = OrderAccess::load_acquire(&_oop_map_cache);
1475   if (oop_map_cache == NULL) {
1476     MutexLockerEx x(OopMapCacheAlloc_lock,  Mutex::_no_safepoint_check_flag);
1477     // Check if _oop_map_cache was allocated while we were waiting for this lock
1478     if ((oop_map_cache = _oop_map_cache) == NULL) {
1479       oop_map_cache = new OopMapCache();
1480       // Ensure _oop_map_cache is stable, since it is examined without a lock
1481       OrderAccess::release_store(&_oop_map_cache, oop_map_cache);
1482     }
1483   }
1484   // _oop_map_cache is constant after init; lookup below does its own locking.
1485   oop_map_cache->lookup(method, bci, entry_for);
1486 }
1487 
1488 
1489 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1490   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1491     Symbol* f_name = fs.name();
1492     Symbol* f_sig  = fs.signature();
1493     if (f_name == name && f_sig == sig) {
1494       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1495       return true;
1496     }
1497   }
1498   return false;
1499 }
1500 
1501 
1502 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1503   const int n = local_interfaces()->length();
1504   for (int i = 0; i < n; i++) {
1505     Klass* intf1 = local_interfaces()->at(i);
1506     assert(intf1->is_interface(), "just checking type");
1507     // search for field in current interface
1508     if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
1509       assert(fd->is_static(), "interface field must be static");
1510       return intf1;
1511     }
1512     // search for field in direct superinterfaces
1513     Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
1514     if (intf2 != NULL) return intf2;
1515   }
1516   // otherwise field lookup fails
1517   return NULL;
1518 }
1519 
1520 
1521 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1522   // search order according to newest JVM spec (5.4.3.2, p.167).
1523   // 1) search for field in current klass
1524   if (find_local_field(name, sig, fd)) {
1525     return const_cast<InstanceKlass*>(this);
1526   }
1527   // 2) search for field recursively in direct superinterfaces
1528   { Klass* intf = find_interface_field(name, sig, fd);
1529     if (intf != NULL) return intf;
1530   }
1531   // 3) apply field lookup recursively if superclass exists
1532   { Klass* supr = super();
1533     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
1534   }
1535   // 4) otherwise field lookup fails
1536   return NULL;
1537 }
1538 
1539 
1540 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1541   // search order according to newest JVM spec (5.4.3.2, p.167).
1542   // 1) search for field in current klass
1543   if (find_local_field(name, sig, fd)) {
1544     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1545   }
1546   // 2) search for field recursively in direct superinterfaces
1547   if (is_static) {
1548     Klass* intf = find_interface_field(name, sig, fd);
1549     if (intf != NULL) return intf;
1550   }
1551   // 3) apply field lookup recursively if superclass exists
1552   { Klass* supr = super();
1553     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
1554   }
1555   // 4) otherwise field lookup fails
1556   return NULL;
1557 }
1558 
1559 
1560 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1561   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1562     if (fs.offset() == offset) {
1563       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1564       if (fd->is_static() == is_static) return true;
1565     }
1566   }
1567   return false;
1568 }
1569 
1570 
1571 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1572   Klass* klass = const_cast<InstanceKlass*>(this);
1573   while (klass != NULL) {
1574     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
1575       return true;
1576     }
1577     klass = klass->super();
1578   }
1579   return false;
1580 }
1581 
1582 
1583 void InstanceKlass::methods_do(void f(Method* method)) {
1584   // Methods aren't stable until they are loaded.  This can be read outside
1585   // a lock through the ClassLoaderData for profiling
1586   if (!is_loaded()) {
1587     return;
1588   }
1589 
1590   int len = methods()->length();
1591   for (int index = 0; index < len; index++) {
1592     Method* m = methods()->at(index);
1593     assert(m->is_method(), "must be method");
1594     f(m);
1595   }
1596 }
1597 
1598 
1599 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
1600   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1601     if (fs.access_flags().is_static()) {
1602       fieldDescriptor& fd = fs.field_descriptor();
1603       cl->do_field(&fd);
1604     }
1605   }
1606 }
1607 
1608 
1609 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
1610   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1611     if (fs.access_flags().is_static()) {
1612       fieldDescriptor& fd = fs.field_descriptor();
1613       f(&fd, mirror, CHECK);
1614     }
1615   }
1616 }
1617 
1618 
1619 static int compare_fields_by_offset(int* a, int* b) {
1620   return a[0] - b[0];
1621 }
1622 
1623 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
1624   InstanceKlass* super = superklass();
1625   if (super != NULL) {
1626     super->do_nonstatic_fields(cl);
1627   }
1628   fieldDescriptor fd;
1629   int length = java_fields_count();
1630   // In DebugInfo nonstatic fields are sorted by offset.
1631   int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
1632   int j = 0;
1633   for (int i = 0; i < length; i += 1) {
1634     fd.reinitialize(this, i);
1635     if (!fd.is_static()) {
1636       fields_sorted[j + 0] = fd.offset();
1637       fields_sorted[j + 1] = i;
1638       j += 2;
1639     }
1640   }
1641   if (j > 0) {
1642     length = j;
1643     // _sort_Fn is defined in growableArray.hpp.
1644     qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
1645     for (int i = 0; i < length; i += 2) {
1646       fd.reinitialize(this, fields_sorted[i + 1]);
1647       assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
1648       cl->do_field(&fd);
1649     }
1650   }
1651   FREE_C_HEAP_ARRAY(int, fields_sorted);
1652 }
1653 
1654 
1655 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
1656   if (array_klasses() != NULL)
1657     ArrayKlass::cast(array_klasses())->array_klasses_do(f);
1658 }
1659 
1660 #ifdef ASSERT
1661 static int linear_search(const Array<Method*>* methods,
1662                          const Symbol* name,
1663                          const Symbol* signature) {
1664   const int len = methods->length();
1665   for (int index = 0; index < len; index++) {
1666     const Method* const m = methods->at(index);
1667     assert(m->is_method(), "must be method");
1668     if (m->signature() == signature && m->name() == name) {
1669        return index;
1670     }
1671   }
1672   return -1;
1673 }
1674 #endif
1675 
1676 static int binary_search(const Array<Method*>* methods, const Symbol* name) {
1677   int len = methods->length();
1678   // methods are sorted, so do binary search
1679   int l = 0;
1680   int h = len - 1;
1681   while (l <= h) {
1682     int mid = (l + h) >> 1;
1683     Method* m = methods->at(mid);
1684     assert(m->is_method(), "must be method");
1685     int res = m->name()->fast_compare(name);
1686     if (res == 0) {
1687       return mid;
1688     } else if (res < 0) {
1689       l = mid + 1;
1690     } else {
1691       h = mid - 1;
1692     }
1693   }
1694   return -1;
1695 }
1696 
1697 // find_method looks up the name/signature in the local methods array
1698 Method* InstanceKlass::find_method(const Symbol* name,
1699                                    const Symbol* signature) const {
1700   return find_method_impl(name, signature, find_overpass, find_static, find_private);
1701 }
1702 
1703 Method* InstanceKlass::find_method_impl(const Symbol* name,
1704                                         const Symbol* signature,
1705                                         OverpassLookupMode overpass_mode,
1706                                         StaticLookupMode static_mode,
1707                                         PrivateLookupMode private_mode) const {
1708   return InstanceKlass::find_method_impl(methods(),
1709                                          name,
1710                                          signature,
1711                                          overpass_mode,
1712                                          static_mode,
1713                                          private_mode);
1714 }
1715 
1716 // find_instance_method looks up the name/signature in the local methods array
1717 // and skips over static methods
1718 Method* InstanceKlass::find_instance_method(const Array<Method*>* methods,
1719                                             const Symbol* name,
1720                                             const Symbol* signature,
1721                                             PrivateLookupMode private_mode) {
1722   Method* const meth = InstanceKlass::find_method_impl(methods,
1723                                                  name,
1724                                                  signature,
1725                                                  find_overpass,
1726                                                  skip_static,
1727                                                  private_mode);
1728   assert(((meth == NULL) || !meth->is_static()),
1729     "find_instance_method should have skipped statics");
1730   return meth;
1731 }
1732 
1733 // find_instance_method looks up the name/signature in the local methods array
1734 // and skips over static methods
1735 Method* InstanceKlass::find_instance_method(const Symbol* name,
1736                                             const Symbol* signature,
1737                                             PrivateLookupMode private_mode) const {
1738   return InstanceKlass::find_instance_method(methods(), name, signature, private_mode);
1739 }
1740 
1741 // Find looks up the name/signature in the local methods array
1742 // and filters on the overpass, static and private flags
1743 // This returns the first one found
1744 // note that the local methods array can have up to one overpass, one static
1745 // and one instance (private or not) with the same name/signature
1746 Method* InstanceKlass::find_local_method(const Symbol* name,
1747                                          const Symbol* signature,
1748                                          OverpassLookupMode overpass_mode,
1749                                          StaticLookupMode static_mode,
1750                                          PrivateLookupMode private_mode) const {
1751   return InstanceKlass::find_method_impl(methods(),
1752                                          name,
1753                                          signature,
1754                                          overpass_mode,
1755                                          static_mode,
1756                                          private_mode);
1757 }
1758 
1759 // Find looks up the name/signature in the local methods array
1760 // and filters on the overpass, static and private flags
1761 // This returns the first one found
1762 // note that the local methods array can have up to one overpass, one static
1763 // and one instance (private or not) with the same name/signature
1764 Method* InstanceKlass::find_local_method(const Array<Method*>* methods,
1765                                          const Symbol* name,
1766                                          const Symbol* signature,
1767                                          OverpassLookupMode overpass_mode,
1768                                          StaticLookupMode static_mode,
1769                                          PrivateLookupMode private_mode) {
1770   return InstanceKlass::find_method_impl(methods,
1771                                          name,
1772                                          signature,
1773                                          overpass_mode,
1774                                          static_mode,
1775                                          private_mode);
1776 }
1777 
1778 Method* InstanceKlass::find_method(const Array<Method*>* methods,
1779                                    const Symbol* name,
1780                                    const Symbol* signature) {
1781   return InstanceKlass::find_method_impl(methods,
1782                                          name,
1783                                          signature,
1784                                          find_overpass,
1785                                          find_static,
1786                                          find_private);
1787 }
1788 
1789 Method* InstanceKlass::find_method_impl(const Array<Method*>* methods,
1790                                         const Symbol* name,
1791                                         const Symbol* signature,
1792                                         OverpassLookupMode overpass_mode,
1793                                         StaticLookupMode static_mode,
1794                                         PrivateLookupMode private_mode) {
1795   int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode);
1796   return hit >= 0 ? methods->at(hit): NULL;
1797 }
1798 
1799 // true if method matches signature and conforms to skipping_X conditions.
1800 static bool method_matches(const Method* m,
1801                            const Symbol* signature,
1802                            bool skipping_overpass,
1803                            bool skipping_static,
1804                            bool skipping_private) {
1805   return ((m->signature() == signature) &&
1806     (!skipping_overpass || !m->is_overpass()) &&
1807     (!skipping_static || !m->is_static()) &&
1808     (!skipping_private || !m->is_private()));
1809 }
1810 
1811 // Used directly for default_methods to find the index into the
1812 // default_vtable_indices, and indirectly by find_method
1813 // find_method_index looks in the local methods array to return the index
1814 // of the matching name/signature. If, overpass methods are being ignored,
1815 // the search continues to find a potential non-overpass match.  This capability
1816 // is important during method resolution to prefer a static method, for example,
1817 // over an overpass method.
1818 // There is the possibility in any _method's array to have the same name/signature
1819 // for a static method, an overpass method and a local instance method
1820 // To correctly catch a given method, the search criteria may need
1821 // to explicitly skip the other two. For local instance methods, it
1822 // is often necessary to skip private methods
1823 int InstanceKlass::find_method_index(const Array<Method*>* methods,
1824                                      const Symbol* name,
1825                                      const Symbol* signature,
1826                                      OverpassLookupMode overpass_mode,
1827                                      StaticLookupMode static_mode,
1828                                      PrivateLookupMode private_mode) {
1829   const bool skipping_overpass = (overpass_mode == skip_overpass);
1830   const bool skipping_static = (static_mode == skip_static);
1831   const bool skipping_private = (private_mode == skip_private);
1832   const int hit = binary_search(methods, name);
1833   if (hit != -1) {
1834     const Method* const m = methods->at(hit);
1835 
1836     // Do linear search to find matching signature.  First, quick check
1837     // for common case, ignoring overpasses if requested.
1838     if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1839       return hit;
1840     }
1841 
1842     // search downwards through overloaded methods
1843     int i;
1844     for (i = hit - 1; i >= 0; --i) {
1845         const Method* const m = methods->at(i);
1846         assert(m->is_method(), "must be method");
1847         if (m->name() != name) {
1848           break;
1849         }
1850         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1851           return i;
1852         }
1853     }
1854     // search upwards
1855     for (i = hit + 1; i < methods->length(); ++i) {
1856         const Method* const m = methods->at(i);
1857         assert(m->is_method(), "must be method");
1858         if (m->name() != name) {
1859           break;
1860         }
1861         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1862           return i;
1863         }
1864     }
1865     // not found
1866 #ifdef ASSERT
1867     const int index = (skipping_overpass || skipping_static || skipping_private) ? -1 :
1868       linear_search(methods, name, signature);
1869     assert(-1 == index, "binary search should have found entry %d", index);
1870 #endif
1871   }
1872   return -1;
1873 }
1874 
1875 int InstanceKlass::find_method_by_name(const Symbol* name, int* end) const {
1876   return find_method_by_name(methods(), name, end);
1877 }
1878 
1879 int InstanceKlass::find_method_by_name(const Array<Method*>* methods,
1880                                        const Symbol* name,
1881                                        int* end_ptr) {
1882   assert(end_ptr != NULL, "just checking");
1883   int start = binary_search(methods, name);
1884   int end = start + 1;
1885   if (start != -1) {
1886     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
1887     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
1888     *end_ptr = end;
1889     return start;
1890   }
1891   return -1;
1892 }
1893 
1894 // uncached_lookup_method searches both the local class methods array and all
1895 // superclasses methods arrays, skipping any overpass methods in superclasses,
1896 // and possibly skipping private methods.
1897 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
1898                                               const Symbol* signature,
1899                                               OverpassLookupMode overpass_mode,
1900                                               PrivateLookupMode private_mode) const {
1901   OverpassLookupMode overpass_local_mode = overpass_mode;
1902   const Klass* klass = this;
1903   while (klass != NULL) {
1904     Method* const method = InstanceKlass::cast(klass)->find_method_impl(name,
1905                                                                         signature,
1906                                                                         overpass_local_mode,
1907                                                                         find_static,
1908                                                                         private_mode);
1909     if (method != NULL) {
1910       return method;
1911     }
1912     klass = klass->super();
1913     overpass_local_mode = skip_overpass;   // Always ignore overpass methods in superclasses
1914   }
1915   return NULL;
1916 }
1917 
1918 #ifdef ASSERT
1919 // search through class hierarchy and return true if this class or
1920 // one of the superclasses was redefined
1921 bool InstanceKlass::has_redefined_this_or_super() const {
1922   const Klass* klass = this;
1923   while (klass != NULL) {
1924     if (InstanceKlass::cast(klass)->has_been_redefined()) {
1925       return true;
1926     }
1927     klass = klass->super();
1928   }
1929   return false;
1930 }
1931 #endif
1932 
1933 // lookup a method in the default methods list then in all transitive interfaces
1934 // Do NOT return private or static methods
1935 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
1936                                                          Symbol* signature) const {
1937   Method* m = NULL;
1938   if (default_methods() != NULL) {
1939     m = find_method(default_methods(), name, signature);
1940   }
1941   // Look up interfaces
1942   if (m == NULL) {
1943     m = lookup_method_in_all_interfaces(name, signature, find_defaults);
1944   }
1945   return m;
1946 }
1947 
1948 // lookup a method in all the interfaces that this class implements
1949 // Do NOT return private or static methods, new in JDK8 which are not externally visible
1950 // They should only be found in the initial InterfaceMethodRef
1951 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
1952                                                        Symbol* signature,
1953                                                        DefaultsLookupMode defaults_mode) const {
1954   Array<InstanceKlass*>* all_ifs = transitive_interfaces();
1955   int num_ifs = all_ifs->length();
1956   InstanceKlass *ik = NULL;
1957   for (int i = 0; i < num_ifs; i++) {
1958     ik = all_ifs->at(i);
1959     Method* m = ik->lookup_method(name, signature);
1960     if (m != NULL && m->is_public() && !m->is_static() &&
1961         ((defaults_mode != skip_defaults) || !m->is_default_method())) {
1962       return m;
1963     }
1964   }
1965   return NULL;
1966 }
1967 
1968 /* jni_id_for_impl for jfieldIds only */
1969 JNIid* InstanceKlass::jni_id_for_impl(int offset) {
1970   MutexLocker ml(JfieldIdCreation_lock);
1971   // Retry lookup after we got the lock
1972   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
1973   if (probe == NULL) {
1974     // Slow case, allocate new static field identifier
1975     probe = new JNIid(this, offset, jni_ids());
1976     set_jni_ids(probe);
1977   }
1978   return probe;
1979 }
1980 
1981 
1982 /* jni_id_for for jfieldIds only */
1983 JNIid* InstanceKlass::jni_id_for(int offset) {
1984   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
1985   if (probe == NULL) {
1986     probe = jni_id_for_impl(offset);
1987   }
1988   return probe;
1989 }
1990 
1991 u2 InstanceKlass::enclosing_method_data(int offset) const {
1992   const Array<jushort>* const inner_class_list = inner_classes();
1993   if (inner_class_list == NULL) {
1994     return 0;
1995   }
1996   const int length = inner_class_list->length();
1997   if (length % inner_class_next_offset == 0) {
1998     return 0;
1999   }
2000   const int index = length - enclosing_method_attribute_size;
2001   assert(offset < enclosing_method_attribute_size, "invalid offset");
2002   return inner_class_list->at(index + offset);
2003 }
2004 
2005 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
2006                                                  u2 method_index) {
2007   Array<jushort>* inner_class_list = inner_classes();
2008   assert (inner_class_list != NULL, "_inner_classes list is not set up");
2009   int length = inner_class_list->length();
2010   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
2011     int index = length - enclosing_method_attribute_size;
2012     inner_class_list->at_put(
2013       index + enclosing_method_class_index_offset, class_index);
2014     inner_class_list->at_put(
2015       index + enclosing_method_method_index_offset, method_index);
2016   }
2017 }
2018 
2019 // Lookup or create a jmethodID.
2020 // This code is called by the VMThread and JavaThreads so the
2021 // locking has to be done very carefully to avoid deadlocks
2022 // and/or other cache consistency problems.
2023 //
2024 jmethodID InstanceKlass::get_jmethod_id(const methodHandle& method_h) {
2025   size_t idnum = (size_t)method_h->method_idnum();
2026   jmethodID* jmeths = methods_jmethod_ids_acquire();
2027   size_t length = 0;
2028   jmethodID id = NULL;
2029 
2030   // We use a double-check locking idiom here because this cache is
2031   // performance sensitive. In the normal system, this cache only
2032   // transitions from NULL to non-NULL which is safe because we use
2033   // release_set_methods_jmethod_ids() to advertise the new cache.
2034   // A partially constructed cache should never be seen by a racing
2035   // thread. We also use release_store() to save a new jmethodID
2036   // in the cache so a partially constructed jmethodID should never be
2037   // seen either. Cache reads of existing jmethodIDs proceed without a
2038   // lock, but cache writes of a new jmethodID requires uniqueness and
2039   // creation of the cache itself requires no leaks so a lock is
2040   // generally acquired in those two cases.
2041   //
2042   // If the RedefineClasses() API has been used, then this cache can
2043   // grow and we'll have transitions from non-NULL to bigger non-NULL.
2044   // Cache creation requires no leaks and we require safety between all
2045   // cache accesses and freeing of the old cache so a lock is generally
2046   // acquired when the RedefineClasses() API has been used.
2047 
2048   if (jmeths != NULL) {
2049     // the cache already exists
2050     if (!idnum_can_increment()) {
2051       // the cache can't grow so we can just get the current values
2052       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
2053     } else {
2054       // cache can grow so we have to be more careful
2055       if (Threads::number_of_threads() == 0 ||
2056           SafepointSynchronize::is_at_safepoint()) {
2057         // we're single threaded or at a safepoint - no locking needed
2058         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
2059       } else {
2060         MutexLocker ml(JmethodIdCreation_lock);
2061         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
2062       }
2063     }
2064   }
2065   // implied else:
2066   // we need to allocate a cache so default length and id values are good
2067 
2068   if (jmeths == NULL ||   // no cache yet
2069       length <= idnum ||  // cache is too short
2070       id == NULL) {       // cache doesn't contain entry
2071 
2072     // This function can be called by the VMThread so we have to do all
2073     // things that might block on a safepoint before grabbing the lock.
2074     // Otherwise, we can deadlock with the VMThread or have a cache
2075     // consistency issue. These vars keep track of what we might have
2076     // to free after the lock is dropped.
2077     jmethodID  to_dealloc_id     = NULL;
2078     jmethodID* to_dealloc_jmeths = NULL;
2079 
2080     // may not allocate new_jmeths or use it if we allocate it
2081     jmethodID* new_jmeths = NULL;
2082     if (length <= idnum) {
2083       // allocate a new cache that might be used
2084       size_t size = MAX2(idnum+1, (size_t)idnum_allocated_count());
2085       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
2086       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
2087       // cache size is stored in element[0], other elements offset by one
2088       new_jmeths[0] = (jmethodID)size;
2089     }
2090 
2091     // allocate a new jmethodID that might be used
2092     jmethodID new_id = NULL;
2093     if (method_h->is_old() && !method_h->is_obsolete()) {
2094       // The method passed in is old (but not obsolete), we need to use the current version
2095       Method* current_method = method_with_idnum((int)idnum);
2096       assert(current_method != NULL, "old and but not obsolete, so should exist");
2097       new_id = Method::make_jmethod_id(class_loader_data(), current_method);
2098     } else {
2099       // It is the current version of the method or an obsolete method,
2100       // use the version passed in
2101       new_id = Method::make_jmethod_id(class_loader_data(), method_h());
2102     }
2103 
2104     if (Threads::number_of_threads() == 0 ||
2105         SafepointSynchronize::is_at_safepoint()) {
2106       // we're single threaded or at a safepoint - no locking needed
2107       id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,
2108                                           &to_dealloc_id, &to_dealloc_jmeths);
2109     } else {
2110       MutexLocker ml(JmethodIdCreation_lock);
2111       id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,
2112                                           &to_dealloc_id, &to_dealloc_jmeths);
2113     }
2114 
2115     // The lock has been dropped so we can free resources.
2116     // Free up either the old cache or the new cache if we allocated one.
2117     if (to_dealloc_jmeths != NULL) {
2118       FreeHeap(to_dealloc_jmeths);
2119     }
2120     // free up the new ID since it wasn't needed
2121     if (to_dealloc_id != NULL) {
2122       Method::destroy_jmethod_id(class_loader_data(), to_dealloc_id);
2123     }
2124   }
2125   return id;
2126 }
2127 
2128 // Figure out how many jmethodIDs haven't been allocated, and make
2129 // sure space for them is pre-allocated.  This makes getting all
2130 // method ids much, much faster with classes with more than 8
2131 // methods, and has a *substantial* effect on performance with jvmti
2132 // code that loads all jmethodIDs for all classes.
2133 void InstanceKlass::ensure_space_for_methodids(int start_offset) {
2134   int new_jmeths = 0;
2135   int length = methods()->length();
2136   for (int index = start_offset; index < length; index++) {
2137     Method* m = methods()->at(index);
2138     jmethodID id = m->find_jmethod_id_or_null();
2139     if (id == NULL) {
2140       new_jmeths++;
2141     }
2142   }
2143   if (new_jmeths != 0) {
2144     Method::ensure_jmethod_ids(class_loader_data(), new_jmeths);
2145   }
2146 }
2147 
2148 // Common code to fetch the jmethodID from the cache or update the
2149 // cache with the new jmethodID. This function should never do anything
2150 // that causes the caller to go to a safepoint or we can deadlock with
2151 // the VMThread or have cache consistency issues.
2152 //
2153 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
2154             size_t idnum, jmethodID new_id,
2155             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
2156             jmethodID** to_dealloc_jmeths_p) {
2157   assert(new_id != NULL, "sanity check");
2158   assert(to_dealloc_id_p != NULL, "sanity check");
2159   assert(to_dealloc_jmeths_p != NULL, "sanity check");
2160   assert(Threads::number_of_threads() == 0 ||
2161          SafepointSynchronize::is_at_safepoint() ||
2162          JmethodIdCreation_lock->owned_by_self(), "sanity check");
2163 
2164   // reacquire the cache - we are locked, single threaded or at a safepoint
2165   jmethodID* jmeths = methods_jmethod_ids_acquire();
2166   jmethodID  id     = NULL;
2167   size_t     length = 0;
2168 
2169   if (jmeths == NULL ||                         // no cache yet
2170       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
2171     if (jmeths != NULL) {
2172       // copy any existing entries from the old cache
2173       for (size_t index = 0; index < length; index++) {
2174         new_jmeths[index+1] = jmeths[index+1];
2175       }
2176       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
2177     }
2178     release_set_methods_jmethod_ids(jmeths = new_jmeths);
2179   } else {
2180     // fetch jmethodID (if any) from the existing cache
2181     id = jmeths[idnum+1];
2182     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
2183   }
2184   if (id == NULL) {
2185     // No matching jmethodID in the existing cache or we have a new
2186     // cache or we just grew the cache. This cache write is done here
2187     // by the first thread to win the foot race because a jmethodID
2188     // needs to be unique once it is generally available.
2189     id = new_id;
2190 
2191     // The jmethodID cache can be read while unlocked so we have to
2192     // make sure the new jmethodID is complete before installing it
2193     // in the cache.
2194     OrderAccess::release_store(&jmeths[idnum+1], id);
2195   } else {
2196     *to_dealloc_id_p = new_id; // save new id for later delete
2197   }
2198   return id;
2199 }
2200 
2201 
2202 // Common code to get the jmethodID cache length and the jmethodID
2203 // value at index idnum if there is one.
2204 //
2205 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
2206        size_t idnum, size_t *length_p, jmethodID* id_p) {
2207   assert(cache != NULL, "sanity check");
2208   assert(length_p != NULL, "sanity check");
2209   assert(id_p != NULL, "sanity check");
2210 
2211   // cache size is stored in element[0], other elements offset by one
2212   *length_p = (size_t)cache[0];
2213   if (*length_p <= idnum) {  // cache is too short
2214     *id_p = NULL;
2215   } else {
2216     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
2217   }
2218 }
2219 
2220 
2221 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
2222 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
2223   size_t idnum = (size_t)method->method_idnum();
2224   jmethodID* jmeths = methods_jmethod_ids_acquire();
2225   size_t length;                                // length assigned as debugging crumb
2226   jmethodID id = NULL;
2227   if (jmeths != NULL &&                         // If there is a cache
2228       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
2229     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
2230   }
2231   return id;
2232 }
2233 
2234 inline DependencyContext InstanceKlass::dependencies() {
2235   DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);
2236   return dep_context;
2237 }
2238 
2239 int InstanceKlass::mark_dependent_nmethods(KlassDepChange& changes) {
2240   return dependencies().mark_dependent_nmethods(changes);
2241 }
2242 
2243 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2244   dependencies().add_dependent_nmethod(nm);
2245 }
2246 
2247 void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
2248   dependencies().remove_dependent_nmethod(nm);
2249 }
2250 
2251 void InstanceKlass::clean_dependency_context() {
2252   dependencies().clean_unloading_dependents();
2253 }
2254 
2255 #ifndef PRODUCT
2256 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2257   dependencies().print_dependent_nmethods(verbose);
2258 }
2259 
2260 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2261   return dependencies().is_dependent_nmethod(nm);
2262 }
2263 #endif //PRODUCT
2264 
2265 void InstanceKlass::clean_weak_instanceklass_links() {
2266   clean_implementors_list();
2267   clean_method_data();
2268 }
2269 
2270 void InstanceKlass::clean_implementors_list() {
2271   assert(is_loader_alive(), "this klass should be live");
2272   if (is_interface()) {
2273     assert (ClassUnloading, "only called for ClassUnloading");
2274     for (;;) {
2275       // Use load_acquire due to competing with inserts
2276       Klass* impl = OrderAccess::load_acquire(adr_implementor());
2277       if (impl != NULL && !impl->is_loader_alive()) {
2278         // NULL this field, might be an unloaded klass or NULL
2279         Klass* volatile* klass = adr_implementor();
2280         if (Atomic::cmpxchg((Klass*)NULL, klass, impl) == impl) {
2281           // Successfully unlinking implementor.
2282           if (log_is_enabled(Trace, class, unload)) {
2283             ResourceMark rm;
2284             log_trace(class, unload)("unlinking class (implementor): %s", impl->external_name());
2285           }
2286           return;
2287         }
2288       } else {
2289         return;
2290       }
2291     }
2292   }
2293 }
2294 
2295 void InstanceKlass::clean_method_data() {
2296   for (int m = 0; m < methods()->length(); m++) {
2297     MethodData* mdo = methods()->at(m)->method_data();
2298     if (mdo != NULL) {
2299       MutexLockerEx ml(SafepointSynchronize::is_at_safepoint() ? NULL : mdo->extra_data_lock());
2300       mdo->clean_method_data(/*always_clean*/false);
2301     }
2302   }
2303 }
2304 
2305 bool InstanceKlass::supers_have_passed_fingerprint_checks() {
2306   if (java_super() != NULL && !java_super()->has_passed_fingerprint_check()) {
2307     ResourceMark rm;
2308     log_trace(class, fingerprint)("%s : super %s not fingerprinted", external_name(), java_super()->external_name());
2309     return false;
2310   }
2311 
2312   Array<InstanceKlass*>* local_interfaces = this->local_interfaces();
2313   if (local_interfaces != NULL) {
2314     int length = local_interfaces->length();
2315     for (int i = 0; i < length; i++) {
2316       InstanceKlass* intf = local_interfaces->at(i);
2317       if (!intf->has_passed_fingerprint_check()) {
2318         ResourceMark rm;
2319         log_trace(class, fingerprint)("%s : interface %s not fingerprinted", external_name(), intf->external_name());
2320         return false;
2321       }
2322     }
2323   }
2324 
2325   return true;
2326 }
2327 
2328 bool InstanceKlass::should_store_fingerprint(bool is_unsafe_anonymous) {
2329 #if INCLUDE_AOT
2330   // We store the fingerprint into the InstanceKlass only in the following 2 cases:
2331   if (CalculateClassFingerprint) {
2332     // (1) We are running AOT to generate a shared library.
2333     return true;
2334   }
2335   if (DumpSharedSpaces) {
2336     // (2) We are running -Xshare:dump to create a shared archive
2337     return true;
2338   }
2339   if (UseAOT && is_unsafe_anonymous) {
2340     // (3) We are using AOT code from a shared library and see an unsafe anonymous class
2341     return true;
2342   }
2343 #endif
2344 
2345   // In all other cases we might set the _misc_has_passed_fingerprint_check bit,
2346   // but do not store the 64-bit fingerprint to save space.
2347   return false;
2348 }
2349 
2350 bool InstanceKlass::has_stored_fingerprint() const {
2351 #if INCLUDE_AOT
2352   return should_store_fingerprint() || is_shared();
2353 #else
2354   return false;
2355 #endif
2356 }
2357 
2358 uint64_t InstanceKlass::get_stored_fingerprint() const {
2359   address adr = adr_fingerprint();
2360   if (adr != NULL) {
2361     return (uint64_t)Bytes::get_native_u8(adr); // adr may not be 64-bit aligned
2362   }
2363   return 0;
2364 }
2365 
2366 void InstanceKlass::store_fingerprint(uint64_t fingerprint) {
2367   address adr = adr_fingerprint();
2368   if (adr != NULL) {
2369     Bytes::put_native_u8(adr, (u8)fingerprint); // adr may not be 64-bit aligned
2370 
2371     ResourceMark rm;
2372     log_trace(class, fingerprint)("stored as " PTR64_FORMAT " for class %s", fingerprint, external_name());
2373   }
2374 }
2375 
2376 void InstanceKlass::metaspace_pointers_do(MetaspaceClosure* it) {
2377   Klass::metaspace_pointers_do(it);
2378 
2379   if (log_is_enabled(Trace, cds)) {
2380     ResourceMark rm;
2381     log_trace(cds)("Iter(InstanceKlass): %p (%s)", this, external_name());
2382   }
2383 
2384   it->push(&_annotations);
2385   it->push((Klass**)&_array_klasses);
2386   it->push(&_constants);
2387   it->push(&_inner_classes);
2388   it->push(&_array_name);
2389 #if INCLUDE_JVMTI
2390   it->push(&_previous_versions);
2391 #endif
2392   it->push(&_methods);
2393   it->push(&_default_methods);
2394   it->push(&_local_interfaces);
2395   it->push(&_transitive_interfaces);
2396   it->push(&_method_ordering);
2397   it->push(&_default_vtable_indices);
2398   it->push(&_fields);
2399 
2400   if (itable_length() > 0) {
2401     itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2402     int method_table_offset_in_words = ioe->offset()/wordSize;
2403     int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2404                          / itableOffsetEntry::size();
2405 
2406     for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2407       if (ioe->interface_klass() != NULL) {
2408         it->push(ioe->interface_klass_addr());
2409         itableMethodEntry* ime = ioe->first_method_entry(this);
2410         int n = klassItable::method_count_for_interface(ioe->interface_klass());
2411         for (int index = 0; index < n; index ++) {
2412           it->push(ime[index].method_addr());
2413         }
2414       }
2415     }
2416   }
2417 
2418   it->push(&_nest_members);
2419 }
2420 
2421 void InstanceKlass::remove_unshareable_info() {
2422   Klass::remove_unshareable_info();
2423 
2424   if (is_in_error_state()) {
2425     // Classes are attempted to link during dumping and may fail,
2426     // but these classes are still in the dictionary and class list in CLD.
2427     // Check in_error state first because in_error is > linked state, so
2428     // is_linked() is true.
2429     // If there's a linking error, there is nothing else to remove.
2430     return;
2431   }
2432 
2433   // Reset to the 'allocated' state to prevent any premature accessing to
2434   // a shared class at runtime while the class is still being loaded and
2435   // restored. A class' init_state is set to 'loaded' at runtime when it's
2436   // being added to class hierarchy (see SystemDictionary:::add_to_hierarchy()).
2437   _init_state = allocated;
2438 
2439   {
2440     MutexLocker ml(Compile_lock);
2441     init_implementor();
2442   }
2443 
2444   constants()->remove_unshareable_info();
2445 
2446   for (int i = 0; i < methods()->length(); i++) {
2447     Method* m = methods()->at(i);
2448     m->remove_unshareable_info();
2449   }
2450 
2451   // do array classes also.
2452   if (array_klasses() != NULL) {
2453     array_klasses()->remove_unshareable_info();
2454   }
2455 
2456   // These are not allocated from metaspace, but they should should all be empty
2457   // during dump time, so we don't need to worry about them in InstanceKlass::iterate().
2458   guarantee(_source_debug_extension == NULL, "must be");
2459   guarantee(_dep_context == NULL, "must be");
2460   guarantee(_osr_nmethods_head == NULL, "must be");
2461 
2462 #if INCLUDE_JVMTI
2463   guarantee(_breakpoints == NULL, "must be");
2464   guarantee(_previous_versions == NULL, "must be");
2465   _cached_class_file = NULL;
2466 #endif
2467 
2468   _init_thread = NULL;
2469   _methods_jmethod_ids = NULL;
2470   _jni_ids = NULL;
2471   _oop_map_cache = NULL;
2472   // clear _nest_host to ensure re-load at runtime
2473   _nest_host = NULL;
2474 }
2475 
2476 void InstanceKlass::remove_java_mirror() {
2477   Klass::remove_java_mirror();
2478 
2479   // do array classes also.
2480   if (array_klasses() != NULL) {
2481     array_klasses()->remove_java_mirror();
2482   }
2483 }
2484 
2485 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
2486   // SystemDictionary::add_to_hierarchy() sets the init_state to loaded
2487   // before the InstanceKlass is added to the SystemDictionary. Make
2488   // sure the current state is <loaded.
2489   assert(!is_loaded(), "invalid init state");
2490   set_package(loader_data, CHECK);
2491   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2492 
2493   Array<Method*>* methods = this->methods();
2494   int num_methods = methods->length();
2495   for (int index = 0; index < num_methods; ++index) {
2496     methods->at(index)->restore_unshareable_info(CHECK);
2497   }
2498   if (JvmtiExport::has_redefined_a_class()) {
2499     // Reinitialize vtable because RedefineClasses may have changed some
2500     // entries in this vtable for super classes so the CDS vtable might
2501     // point to old or obsolete entries.  RedefineClasses doesn't fix up
2502     // vtables in the shared system dictionary, only the main one.
2503     // It also redefines the itable too so fix that too.
2504     vtable().initialize_vtable(false, CHECK);
2505     itable().initialize_itable(false, CHECK);
2506   }
2507 
2508   // restore constant pool resolved references
2509   constants()->restore_unshareable_info(CHECK);
2510 
2511   if (array_klasses() != NULL) {
2512     // Array classes have null protection domain.
2513     // --> see ArrayKlass::complete_create_array_klass()
2514     array_klasses()->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);
2515   }
2516 }
2517 
2518 // returns true IFF is_in_error_state() has been changed as a result of this call.
2519 bool InstanceKlass::check_sharing_error_state() {
2520   assert(DumpSharedSpaces, "should only be called during dumping");
2521   bool old_state = is_in_error_state();
2522 
2523   if (!is_in_error_state()) {
2524     bool bad = false;
2525     for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) {
2526       if (sup->is_in_error_state()) {
2527         bad = true;
2528         break;
2529       }
2530     }
2531     if (!bad) {
2532       Array<InstanceKlass*>* interfaces = transitive_interfaces();
2533       for (int i = 0; i < interfaces->length(); i++) {
2534         InstanceKlass* iface = interfaces->at(i);
2535         if (iface->is_in_error_state()) {
2536           bad = true;
2537           break;
2538         }
2539       }
2540     }
2541 
2542     if (bad) {
2543       set_in_error_state();
2544     }
2545   }
2546 
2547   return (old_state != is_in_error_state());
2548 }
2549 
2550 #if INCLUDE_JVMTI
2551 static void clear_all_breakpoints(Method* m) {
2552   m->clear_all_breakpoints();
2553 }
2554 #endif
2555 
2556 void InstanceKlass::unload_class(InstanceKlass* ik) {
2557   // Release dependencies.
2558   ik->dependencies().remove_all_dependents();
2559 
2560   // notify the debugger
2561   if (JvmtiExport::should_post_class_unload()) {
2562     JvmtiExport::post_class_unload(ik);
2563   }
2564 
2565   // notify ClassLoadingService of class unload
2566   ClassLoadingService::notify_class_unloaded(ik);
2567 
2568   if (log_is_enabled(Info, class, unload)) {
2569     ResourceMark rm;
2570     log_info(class, unload)("unloading class %s " INTPTR_FORMAT, ik->external_name(), p2i(ik));
2571   }
2572 
2573   Events::log_class_unloading(Thread::current(), ik);
2574 
2575 #if INCLUDE_JFR
2576   assert(ik != NULL, "invariant");
2577   EventClassUnload event;
2578   event.set_unloadedClass(ik);
2579   event.set_definingClassLoader(ik->class_loader_data());
2580   event.commit();
2581 #endif
2582 }
2583 
2584 void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {
2585   // Clean up C heap
2586   ik->release_C_heap_structures();
2587   ik->constants()->release_C_heap_structures();
2588 }
2589 
2590 void InstanceKlass::release_C_heap_structures() {
2591   // Can't release the constant pool here because the constant pool can be
2592   // deallocated separately from the InstanceKlass for default methods and
2593   // redefine classes.
2594 
2595   // Deallocate oop map cache
2596   if (_oop_map_cache != NULL) {
2597     delete _oop_map_cache;
2598     _oop_map_cache = NULL;
2599   }
2600 
2601   // Deallocate JNI identifiers for jfieldIDs
2602   JNIid::deallocate(jni_ids());
2603   set_jni_ids(NULL);
2604 
2605   jmethodID* jmeths = methods_jmethod_ids_acquire();
2606   if (jmeths != (jmethodID*)NULL) {
2607     release_set_methods_jmethod_ids(NULL);
2608     FreeHeap(jmeths);
2609   }
2610 
2611   assert(_dep_context == NULL,
2612          "dependencies should already be cleaned");
2613 
2614 #if INCLUDE_JVMTI
2615   // Deallocate breakpoint records
2616   if (breakpoints() != 0x0) {
2617     methods_do(clear_all_breakpoints);
2618     assert(breakpoints() == 0x0, "should have cleared breakpoints");
2619   }
2620 
2621   // deallocate the cached class file
2622   if (_cached_class_file != NULL) {
2623     os::free(_cached_class_file);
2624     _cached_class_file = NULL;
2625   }
2626 #endif
2627 
2628   // Decrement symbol reference counts associated with the unloaded class.
2629   if (_name != NULL) _name->decrement_refcount();
2630   // unreference array name derived from this class name (arrays of an unloaded
2631   // class can't be referenced anymore).
2632   if (_array_name != NULL)  _array_name->decrement_refcount();
2633   if (_value_types != NULL) {
2634     for (int i = 0; i < _value_types->length(); i++) {
2635       Symbol* s = _value_types->at(i)._class_name;
2636       if (s != NULL) {
2637         s->decrement_refcount();
2638       }
2639     }
2640   }
2641   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension);
2642 }
2643 
2644 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
2645   if (array == NULL) {
2646     _source_debug_extension = NULL;
2647   } else {
2648     // Adding one to the attribute length in order to store a null terminator
2649     // character could cause an overflow because the attribute length is
2650     // already coded with an u4 in the classfile, but in practice, it's
2651     // unlikely to happen.
2652     assert((length+1) > length, "Overflow checking");
2653     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2654     for (int i = 0; i < length; i++) {
2655       sde[i] = array[i];
2656     }
2657     sde[length] = '\0';
2658     _source_debug_extension = sde;
2659   }
2660 }
2661 
2662 const char* InstanceKlass::signature_name() const {
2663   return signature_name_of(is_value() ? 'Q' : 'L');
2664 }
2665 
2666 const char* InstanceKlass::signature_name_of(char c) const {
2667   int hash_len = 0;
2668   char hash_buf[40];
2669 
2670   // If this is an unsafe anonymous class, append a hash to make the name unique
2671   if (is_unsafe_anonymous()) {
2672     intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
2673     jio_snprintf(hash_buf, sizeof(hash_buf), "/" UINTX_FORMAT, (uintx)hash);
2674     hash_len = (int)strlen(hash_buf);
2675   }
2676 
2677   // Get the internal name as a c string
2678   const char* src = (const char*) (name()->as_C_string());
2679   const int src_length = (int)strlen(src);
2680 
2681   char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
2682 
2683   // Add L or Q as type indicator
2684   int dest_index = 0;
2685   dest[dest_index++] = c;
2686 
2687   // Add the actual class name
2688   for (int src_index = 0; src_index < src_length; ) {
2689     dest[dest_index++] = src[src_index++];
2690   }
2691 
2692   // If we have a hash, append it
2693   for (int hash_index = 0; hash_index < hash_len; ) {
2694     dest[dest_index++] = hash_buf[hash_index++];
2695   }
2696 
2697   // Add the semicolon and the NULL
2698   dest[dest_index++] = ';';
2699   dest[dest_index] = '\0';
2700   return dest;
2701 }
2702 
2703 // Used to obtain the package name from a fully qualified class name.
2704 Symbol* InstanceKlass::package_from_name(const Symbol* name, TRAPS) {
2705   if (name == NULL) {
2706     return NULL;
2707   } else {
2708     if (name->utf8_length() <= 0) {
2709       return NULL;
2710     }
2711     ResourceMark rm;
2712     const char* package_name = ClassLoader::package_from_name((const char*) name->as_C_string());
2713     if (package_name == NULL) {
2714       return NULL;
2715     }
2716     Symbol* pkg_name = SymbolTable::new_symbol(package_name, THREAD);
2717     return pkg_name;
2718   }
2719 }
2720 
2721 ModuleEntry* InstanceKlass::module() const {
2722   // For an unsafe anonymous class return the host class' module
2723   if (is_unsafe_anonymous()) {
2724     assert(unsafe_anonymous_host() != NULL, "unsafe anonymous class must have a host class");
2725     return unsafe_anonymous_host()->module();
2726   }
2727 
2728   // Class is in a named package
2729   if (!in_unnamed_package()) {
2730     return _package_entry->module();
2731   }
2732 
2733   // Class is in an unnamed package, return its loader's unnamed module
2734   return class_loader_data()->unnamed_module();
2735 }
2736 
2737 void InstanceKlass::set_package(ClassLoaderData* loader_data, TRAPS) {
2738 
2739   // ensure java/ packages only loaded by boot or platform builtin loaders
2740   check_prohibited_package(name(), loader_data, CHECK);
2741 
2742   TempNewSymbol pkg_name = package_from_name(name(), CHECK);
2743 
2744   if (pkg_name != NULL && loader_data != NULL) {
2745 
2746     // Find in class loader's package entry table.
2747     _package_entry = loader_data->packages()->lookup_only(pkg_name);
2748 
2749     // If the package name is not found in the loader's package
2750     // entry table, it is an indication that the package has not
2751     // been defined. Consider it defined within the unnamed module.
2752     if (_package_entry == NULL) {
2753       ResourceMark rm;
2754 
2755       if (!ModuleEntryTable::javabase_defined()) {
2756         // Before java.base is defined during bootstrapping, define all packages in
2757         // the java.base module.  If a non-java.base package is erroneously placed
2758         // in the java.base module it will be caught later when java.base
2759         // is defined by ModuleEntryTable::verify_javabase_packages check.
2760         assert(ModuleEntryTable::javabase_moduleEntry() != NULL, JAVA_BASE_NAME " module is NULL");
2761         _package_entry = loader_data->packages()->lookup(pkg_name, ModuleEntryTable::javabase_moduleEntry());
2762       } else {
2763         assert(loader_data->unnamed_module() != NULL, "unnamed module is NULL");
2764         _package_entry = loader_data->packages()->lookup(pkg_name,
2765                                                          loader_data->unnamed_module());
2766       }
2767 
2768       // A package should have been successfully created
2769       assert(_package_entry != NULL, "Package entry for class %s not found, loader %s",
2770              name()->as_C_string(), loader_data->loader_name_and_id());
2771     }
2772 
2773     if (log_is_enabled(Debug, module)) {
2774       ResourceMark rm;
2775       ModuleEntry* m = _package_entry->module();
2776       log_trace(module)("Setting package: class: %s, package: %s, loader: %s, module: %s",
2777                         external_name(),
2778                         pkg_name->as_C_string(),
2779                         loader_data->loader_name_and_id(),
2780                         (m->is_named() ? m->name()->as_C_string() : UNNAMED_MODULE));
2781     }
2782   } else {
2783     ResourceMark rm;
2784     log_trace(module)("Setting package: class: %s, package: unnamed, loader: %s, module: %s",
2785                       external_name(),
2786                       (loader_data != NULL) ? loader_data->loader_name_and_id() : "NULL",
2787                       UNNAMED_MODULE);
2788   }
2789 }
2790 
2791 
2792 // different versions of is_same_class_package
2793 
2794 bool InstanceKlass::is_same_class_package(const Klass* class2) const {
2795   oop classloader1 = this->class_loader();
2796   PackageEntry* classpkg1 = this->package();
2797   if (class2->is_objArray_klass()) {
2798     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
2799   }
2800 
2801   oop classloader2;
2802   PackageEntry* classpkg2;
2803   if (class2->is_instance_klass()) {
2804     classloader2 = class2->class_loader();
2805     classpkg2 = class2->package();
2806   } else {
2807     assert(class2->is_typeArray_klass(), "should be type array");
2808     classloader2 = NULL;
2809     classpkg2 = NULL;
2810   }
2811 
2812   // Same package is determined by comparing class loader
2813   // and package entries. Both must be the same. This rule
2814   // applies even to classes that are defined in the unnamed
2815   // package, they still must have the same class loader.
2816   if (oopDesc::equals(classloader1, classloader2) && (classpkg1 == classpkg2)) {
2817     return true;
2818   }
2819 
2820   return false;
2821 }
2822 
2823 // return true if this class and other_class are in the same package. Classloader
2824 // and classname information is enough to determine a class's package
2825 bool InstanceKlass::is_same_class_package(oop other_class_loader,
2826                                           const Symbol* other_class_name) const {
2827   if (!oopDesc::equals(class_loader(), other_class_loader)) {
2828     return false;
2829   }
2830   if (name()->fast_compare(other_class_name) == 0) {
2831      return true;
2832   }
2833 
2834   {
2835     ResourceMark rm;
2836 
2837     bool bad_class_name = false;
2838     const char* other_pkg =
2839       ClassLoader::package_from_name((const char*) other_class_name->as_C_string(), &bad_class_name);
2840     if (bad_class_name) {
2841       return false;
2842     }
2843     // Check that package_from_name() returns NULL, not "", if there is no package.
2844     assert(other_pkg == NULL || strlen(other_pkg) > 0, "package name is empty string");
2845 
2846     const Symbol* const this_package_name =
2847       this->package() != NULL ? this->package()->name() : NULL;
2848 
2849     if (this_package_name == NULL || other_pkg == NULL) {
2850       // One of the two doesn't have a package.  Only return true if the other
2851       // one also doesn't have a package.
2852       return (const char*)this_package_name == other_pkg;
2853     }
2854 
2855     // Check if package is identical
2856     return this_package_name->equals(other_pkg);
2857   }
2858 }
2859 
2860 // Returns true iff super_method can be overridden by a method in targetclassname
2861 // See JLS 3rd edition 8.4.6.1
2862 // Assumes name-signature match
2863 // "this" is InstanceKlass of super_method which must exist
2864 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
2865 bool InstanceKlass::is_override(const methodHandle& super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
2866    // Private methods can not be overridden
2867    if (super_method->is_private()) {
2868      return false;
2869    }
2870    // If super method is accessible, then override
2871    if ((super_method->is_protected()) ||
2872        (super_method->is_public())) {
2873      return true;
2874    }
2875    // Package-private methods are not inherited outside of package
2876    assert(super_method->is_package_private(), "must be package private");
2877    return(is_same_class_package(targetclassloader(), targetclassname));
2878 }
2879 
2880 // Only boot and platform class loaders can define classes in "java/" packages.
2881 void InstanceKlass::check_prohibited_package(Symbol* class_name,
2882                                              ClassLoaderData* loader_data,
2883                                              TRAPS) {
2884   if (!loader_data->is_boot_class_loader_data() &&
2885       !loader_data->is_platform_class_loader_data() &&
2886       class_name != NULL) {
2887     ResourceMark rm(THREAD);
2888     char* name = class_name->as_C_string();
2889     if (strncmp(name, JAVAPKG, JAVAPKG_LEN) == 0 && name[JAVAPKG_LEN] == '/') {
2890       TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK);
2891       assert(pkg_name != NULL, "Error in parsing package name starting with 'java/'");
2892       name = pkg_name->as_C_string();
2893       const char* class_loader_name = loader_data->loader_name_and_id();
2894       StringUtils::replace_no_expand(name, "/", ".");
2895       const char* msg_text1 = "Class loader (instance of): ";
2896       const char* msg_text2 = " tried to load prohibited package name: ";
2897       size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + strlen(name) + 1;
2898       char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len);
2899       jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, name);
2900       THROW_MSG(vmSymbols::java_lang_SecurityException(), message);
2901     }
2902   }
2903   return;
2904 }
2905 
2906 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
2907   constantPoolHandle i_cp(THREAD, constants());
2908   for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
2909     int ioff = iter.inner_class_info_index();
2910     if (ioff != 0) {
2911       // Check to see if the name matches the class we're looking for
2912       // before attempting to find the class.
2913       if (i_cp->klass_name_at_matches(this, ioff)) {
2914         Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
2915         if (this == inner_klass) {
2916           *ooff = iter.outer_class_info_index();
2917           *noff = iter.inner_name_index();
2918           return true;
2919         }
2920       }
2921     }
2922   }
2923   return false;
2924 }
2925 
2926 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
2927   InstanceKlass* outer_klass = NULL;
2928   *inner_is_member = false;
2929   int ooff = 0, noff = 0;
2930   bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
2931   if (has_inner_classes_attr) {
2932     constantPoolHandle i_cp(THREAD, constants());
2933     if (ooff != 0) {
2934       Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
2935       outer_klass = InstanceKlass::cast(ok);
2936       *inner_is_member = true;
2937     }
2938     if (NULL == outer_klass) {
2939       // It may be unsafe anonymous; try for that.
2940       int encl_method_class_idx = enclosing_method_class_index();
2941       if (encl_method_class_idx != 0) {
2942         Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
2943         outer_klass = InstanceKlass::cast(ok);
2944         *inner_is_member = false;
2945       }
2946     }
2947   }
2948 
2949   // If no inner class attribute found for this class.
2950   if (NULL == outer_klass) return NULL;
2951 
2952   // Throws an exception if outer klass has not declared k as an inner klass
2953   // We need evidence that each klass knows about the other, or else
2954   // the system could allow a spoof of an inner class to gain access rights.
2955   Reflection::check_for_inner_class(outer_klass, this, *inner_is_member, CHECK_NULL);
2956   return outer_klass;
2957 }
2958 
2959 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
2960   jint access = access_flags().as_int();
2961 
2962   // But check if it happens to be member class.
2963   InnerClassesIterator iter(this);
2964   for (; !iter.done(); iter.next()) {
2965     int ioff = iter.inner_class_info_index();
2966     // Inner class attribute can be zero, skip it.
2967     // Strange but true:  JVM spec. allows null inner class refs.
2968     if (ioff == 0) continue;
2969 
2970     // only look at classes that are already loaded
2971     // since we are looking for the flags for our self.
2972     Symbol* inner_name = constants()->klass_name_at(ioff);
2973     if (name() == inner_name) {
2974       // This is really a member class.
2975       access = iter.inner_access_flags();
2976       break;
2977     }
2978   }
2979   // Remember to strip ACC_SUPER bit
2980   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
2981 }
2982 
2983 jint InstanceKlass::jvmti_class_status() const {
2984   jint result = 0;
2985 
2986   if (is_linked()) {
2987     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
2988   }
2989 
2990   if (is_initialized()) {
2991     assert(is_linked(), "Class status is not consistent");
2992     result |= JVMTI_CLASS_STATUS_INITIALIZED;
2993   }
2994   if (is_in_error_state()) {
2995     result |= JVMTI_CLASS_STATUS_ERROR;
2996   }
2997   return result;
2998 }
2999 
3000 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
3001   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
3002   int method_table_offset_in_words = ioe->offset()/wordSize;
3003   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
3004                        / itableOffsetEntry::size();
3005 
3006   for (int cnt = 0 ; ; cnt ++, ioe ++) {
3007     // If the interface isn't implemented by the receiver class,
3008     // the VM should throw IncompatibleClassChangeError.
3009     if (cnt >= nof_interfaces) {
3010       ResourceMark rm(THREAD);
3011       stringStream ss;
3012       bool same_module = (module() == holder->module());
3013       ss.print("Receiver class %s does not implement "
3014                "the interface %s defining the method to be called "
3015                "(%s%s%s)",
3016                external_name(), holder->external_name(),
3017                (same_module) ? joint_in_module_of_loader(holder) : class_in_module_of_loader(),
3018                (same_module) ? "" : "; ",
3019                (same_module) ? "" : holder->class_in_module_of_loader());
3020       THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
3021     }
3022 
3023     Klass* ik = ioe->interface_klass();
3024     if (ik == holder) break;
3025   }
3026 
3027   itableMethodEntry* ime = ioe->first_method_entry(this);
3028   Method* m = ime[index].method();
3029   if (m == NULL) {
3030     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
3031   }
3032   return m;
3033 }
3034 
3035 
3036 #if INCLUDE_JVMTI
3037 // update default_methods for redefineclasses for methods that are
3038 // not yet in the vtable due to concurrent subclass define and superinterface
3039 // redefinition
3040 // Note: those in the vtable, should have been updated via adjust_method_entries
3041 void InstanceKlass::adjust_default_methods(bool* trace_name_printed) {
3042   // search the default_methods for uses of either obsolete or EMCP methods
3043   if (default_methods() != NULL) {
3044     for (int index = 0; index < default_methods()->length(); index ++) {
3045       Method* old_method = default_methods()->at(index);
3046       if (old_method == NULL || !old_method->is_old()) {
3047         continue; // skip uninteresting entries
3048       }
3049       assert(!old_method->is_deleted(), "default methods may not be deleted");
3050       Method* new_method = old_method->get_new_method();
3051       default_methods()->at_put(index, new_method);
3052 
3053       if (log_is_enabled(Info, redefine, class, update)) {
3054         ResourceMark rm;
3055         if (!(*trace_name_printed)) {
3056           log_info(redefine, class, update)
3057             ("adjust: klassname=%s default methods from name=%s",
3058              external_name(), old_method->method_holder()->external_name());
3059           *trace_name_printed = true;
3060         }
3061         log_debug(redefine, class, update, vtables)
3062           ("default method update: %s(%s) ",
3063            new_method->name()->as_C_string(), new_method->signature()->as_C_string());
3064       }
3065     }
3066   }
3067 }
3068 #endif // INCLUDE_JVMTI
3069 
3070 // On-stack replacement stuff
3071 void InstanceKlass::add_osr_nmethod(nmethod* n) {
3072   // only one compilation can be active
3073   {
3074     // This is a short non-blocking critical region, so the no safepoint check is ok.
3075     MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
3076     assert(n->is_osr_method(), "wrong kind of nmethod");
3077     n->set_osr_link(osr_nmethods_head());
3078     set_osr_nmethods_head(n);
3079     // Raise the highest osr level if necessary
3080     if (TieredCompilation) {
3081       Method* m = n->method();
3082       m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
3083     }
3084   }
3085 
3086   // Get rid of the osr methods for the same bci that have lower levels.
3087   if (TieredCompilation) {
3088     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
3089       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
3090       if (inv != NULL && inv->is_in_use()) {
3091         inv->make_not_entrant();
3092       }
3093     }
3094   }
3095 }
3096 
3097 // Remove osr nmethod from the list. Return true if found and removed.
3098 bool InstanceKlass::remove_osr_nmethod(nmethod* n) {
3099   // This is a short non-blocking critical region, so the no safepoint check is ok.
3100   MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
3101   assert(n->is_osr_method(), "wrong kind of nmethod");
3102   nmethod* last = NULL;
3103   nmethod* cur  = osr_nmethods_head();
3104   int max_level = CompLevel_none;  // Find the max comp level excluding n
3105   Method* m = n->method();
3106   // Search for match
3107   bool found = false;
3108   while(cur != NULL && cur != n) {
3109     if (TieredCompilation && m == cur->method()) {
3110       // Find max level before n
3111       max_level = MAX2(max_level, cur->comp_level());
3112     }
3113     last = cur;
3114     cur = cur->osr_link();
3115   }
3116   nmethod* next = NULL;
3117   if (cur == n) {
3118     found = true;
3119     next = cur->osr_link();
3120     if (last == NULL) {
3121       // Remove first element
3122       set_osr_nmethods_head(next);
3123     } else {
3124       last->set_osr_link(next);
3125     }
3126   }
3127   n->set_osr_link(NULL);
3128   if (TieredCompilation) {
3129     cur = next;
3130     while (cur != NULL) {
3131       // Find max level after n
3132       if (m == cur->method()) {
3133         max_level = MAX2(max_level, cur->comp_level());
3134       }
3135       cur = cur->osr_link();
3136     }
3137     m->set_highest_osr_comp_level(max_level);
3138   }
3139   return found;
3140 }
3141 
3142 int InstanceKlass::mark_osr_nmethods(const Method* m) {
3143   // This is a short non-blocking critical region, so the no safepoint check is ok.
3144   MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
3145   nmethod* osr = osr_nmethods_head();
3146   int found = 0;
3147   while (osr != NULL) {
3148     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3149     if (osr->method() == m) {
3150       osr->mark_for_deoptimization();
3151       found++;
3152     }
3153     osr = osr->osr_link();
3154   }
3155   return found;
3156 }
3157 
3158 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
3159   // This is a short non-blocking critical region, so the no safepoint check is ok.
3160   MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
3161   nmethod* osr = osr_nmethods_head();
3162   nmethod* best = NULL;
3163   while (osr != NULL) {
3164     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3165     // There can be a time when a c1 osr method exists but we are waiting
3166     // for a c2 version. When c2 completes its osr nmethod we will trash
3167     // the c1 version and only be able to find the c2 version. However
3168     // while we overflow in the c1 code at back branches we don't want to
3169     // try and switch to the same code as we are already running
3170 
3171     if (osr->method() == m &&
3172         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
3173       if (match_level) {
3174         if (osr->comp_level() == comp_level) {
3175           // Found a match - return it.
3176           return osr;
3177         }
3178       } else {
3179         if (best == NULL || (osr->comp_level() > best->comp_level())) {
3180           if (osr->comp_level() == CompLevel_highest_tier) {
3181             // Found the best possible - return it.
3182             return osr;
3183           }
3184           best = osr;
3185         }
3186       }
3187     }
3188     osr = osr->osr_link();
3189   }
3190   if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
3191     return best;
3192   }
3193   return NULL;
3194 }
3195 
3196 // -----------------------------------------------------------------------------------------------------
3197 // Printing
3198 
3199 #ifndef PRODUCT
3200 
3201 #define BULLET  " - "
3202 
3203 static const char* state_names[] = {
3204   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3205 };
3206 
3207 static void print_vtable(address self, intptr_t* start, int len, outputStream* st) {
3208   ResourceMark rm;
3209   int* forward_refs = NEW_RESOURCE_ARRAY(int, len);
3210   for (int i = 0; i < len; i++)  forward_refs[i] = 0;
3211   for (int i = 0; i < len; i++) {
3212     intptr_t e = start[i];
3213     st->print("%d : " INTPTR_FORMAT, i, e);
3214     if (forward_refs[i] != 0) {
3215       int from = forward_refs[i];
3216       int off = (int) start[from];
3217       st->print(" (offset %d <= [%d])", off, from);
3218     }
3219     if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {
3220       st->print(" ");
3221       ((Metadata*)e)->print_value_on(st);
3222     } else if (self != NULL && e > 0 && e < 0x10000) {
3223       address location = self + e;
3224       int index = (int)((intptr_t*)location - start);
3225       st->print(" (offset %d => [%d])", (int)e, index);
3226       if (index >= 0 && index < len)
3227         forward_refs[index] = i;
3228     }
3229     st->cr();
3230   }
3231 }
3232 
3233 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3234   return print_vtable(NULL, reinterpret_cast<intptr_t*>(start), len, st);
3235 }
3236 
3237 template<typename T>
3238  static void print_array_on(outputStream* st, Array<T>* array) {
3239    if (array == NULL) { st->print_cr("NULL"); return; }
3240    array->print_value_on(st); st->cr();
3241    if (Verbose || WizardMode) {
3242      for (int i = 0; i < array->length(); i++) {
3243        st->print("%d : ", i); array->at(i)->print_value_on(st); st->cr();
3244      }
3245    }
3246  }
3247 
3248 static void print_array_on(outputStream* st, Array<int>* array) {
3249   if (array == NULL) { st->print_cr("NULL"); return; }
3250   array->print_value_on(st); st->cr();
3251   if (Verbose || WizardMode) {
3252     for (int i = 0; i < array->length(); i++) {
3253       st->print("%d : %d", i, array->at(i)); st->cr();
3254     }
3255   }
3256 }
3257 
3258 void InstanceKlass::print_on(outputStream* st) const {
3259   assert(is_klass(), "must be klass");
3260   Klass::print_on(st);
3261 
3262   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3263   st->print(BULLET"klass size:        %d", size());                               st->cr();
3264   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
3265   st->print(BULLET"misc flags:        0x%x", _misc_flags);                        st->cr();
3266   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
3267   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3268   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3269   st->print(BULLET"sub:               ");
3270   Klass* sub = subklass();
3271   int n;
3272   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
3273     if (n < MaxSubklassPrintSize) {
3274       sub->print_value_on(st);
3275       st->print("   ");
3276     }
3277   }
3278   if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize);
3279   st->cr();
3280 
3281   if (is_interface()) {
3282     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
3283     if (nof_implementors() == 1) {
3284       st->print_cr(BULLET"implementor:    ");
3285       st->print("   ");
3286       implementor()->print_value_on(st);
3287       st->cr();
3288     }
3289   }
3290 
3291   st->print(BULLET"arrays:            "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3292   st->print(BULLET"methods:           "); print_array_on(st, methods());
3293   st->print(BULLET"method ordering:   "); print_array_on(st, method_ordering());
3294   st->print(BULLET"default_methods:   "); print_array_on(st, default_methods());
3295   if (default_vtable_indices() != NULL) {
3296     st->print(BULLET"default vtable indices:   "); print_array_on(st, default_vtable_indices());
3297   }
3298   st->print(BULLET"local interfaces:  "); print_array_on(st, local_interfaces());
3299   st->print(BULLET"trans. interfaces: "); print_array_on(st, transitive_interfaces());
3300   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
3301   if (class_loader_data() != NULL) {
3302     st->print(BULLET"class loader data:  ");
3303     class_loader_data()->print_value_on(st);
3304     st->cr();
3305   }
3306   st->print(BULLET"unsafe anonymous host class:        "); Metadata::print_value_on_maybe_null(st, unsafe_anonymous_host()); st->cr();
3307   if (source_file_name() != NULL) {
3308     st->print(BULLET"source file:       ");
3309     source_file_name()->print_value_on(st);
3310     st->cr();
3311   }
3312   if (source_debug_extension() != NULL) {
3313     st->print(BULLET"source debug extension:       ");
3314     st->print("%s", source_debug_extension());
3315     st->cr();
3316   }
3317   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
3318   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
3319   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
3320   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
3321   {
3322     bool have_pv = false;
3323     // previous versions are linked together through the InstanceKlass
3324     for (InstanceKlass* pv_node = previous_versions();
3325          pv_node != NULL;
3326          pv_node = pv_node->previous_versions()) {
3327       if (!have_pv)
3328         st->print(BULLET"previous version:  ");
3329       have_pv = true;
3330       pv_node->constants()->print_value_on(st);
3331     }
3332     if (have_pv) st->cr();
3333   }
3334 
3335   if (generic_signature() != NULL) {
3336     st->print(BULLET"generic signature: ");
3337     generic_signature()->print_value_on(st);
3338     st->cr();
3339   }
3340   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
3341   st->print(BULLET"nest members:     "); nest_members()->print_value_on(st);     st->cr();
3342   if (java_mirror() != NULL) {
3343     st->print(BULLET"java mirror:       ");
3344     java_mirror()->print_value_on(st);
3345     st->cr();
3346   } else {
3347     st->print_cr(BULLET"java mirror:       NULL");
3348   }
3349   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3350   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
3351   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3352   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(NULL, start_of_itable(), itable_length(), st);
3353   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3354   FieldPrinter print_static_field(st);
3355   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3356   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3357   FieldPrinter print_nonstatic_field(st);
3358   InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3359   ik->do_nonstatic_fields(&print_nonstatic_field);
3360 
3361   st->print(BULLET"non-static oop maps: ");
3362   OopMapBlock* map     = start_of_nonstatic_oop_maps();
3363   OopMapBlock* end_map = map + nonstatic_oop_map_count();
3364   while (map < end_map) {
3365     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3366     map++;
3367   }
3368   st->cr();
3369 }
3370 
3371 #endif //PRODUCT
3372 
3373 void InstanceKlass::print_value_on(outputStream* st) const {
3374   assert(is_klass(), "must be klass");
3375   if (Verbose || WizardMode)  access_flags().print_on(st);
3376   name()->print_value_on(st);
3377 }
3378 
3379 #ifndef PRODUCT
3380 
3381 void FieldPrinter::do_field(fieldDescriptor* fd) {
3382   _st->print(BULLET);
3383    if (_obj == NULL) {
3384      fd->print_on(_st);
3385      _st->cr();
3386    } else {
3387      fd->print_on_for(_st, _obj);
3388      _st->cr();
3389    }
3390 }
3391 
3392 
3393 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3394   Klass::oop_print_on(obj, st);
3395 
3396   if (this == SystemDictionary::String_klass()) {
3397     typeArrayOop value  = java_lang_String::value(obj);
3398     juint        length = java_lang_String::length(obj);
3399     if (value != NULL &&
3400         value->is_typeArray() &&
3401         length <= (juint) value->length()) {
3402       st->print(BULLET"string: ");
3403       java_lang_String::print(obj, st);
3404       st->cr();
3405       if (!WizardMode)  return;  // that is enough
3406     }
3407   }
3408 
3409   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
3410   FieldPrinter print_field(st, obj);
3411   do_nonstatic_fields(&print_field);
3412 
3413   if (this == SystemDictionary::Class_klass()) {
3414     st->print(BULLET"signature: ");
3415     java_lang_Class::print_signature(obj, st);
3416     st->cr();
3417     Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
3418     st->print(BULLET"fake entry for mirror: ");
3419     Metadata::print_value_on_maybe_null(st, mirrored_klass);
3420     st->cr();
3421     Klass* array_klass = java_lang_Class::array_klass_acquire(obj);
3422     st->print(BULLET"fake entry for array: ");
3423     Metadata::print_value_on_maybe_null(st, array_klass);
3424     st->cr();
3425     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
3426     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
3427     Klass* real_klass = java_lang_Class::as_Klass(obj);
3428     if (real_klass != NULL && real_klass->is_instance_klass()) {
3429       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3430     }
3431   } else if (this == SystemDictionary::MethodType_klass()) {
3432     st->print(BULLET"signature: ");
3433     java_lang_invoke_MethodType::print_signature(obj, st);
3434     st->cr();
3435   }
3436 }
3437 
3438 bool InstanceKlass::verify_itable_index(int i) {
3439   int method_count = klassItable::method_count_for_interface(this);
3440   assert(i >= 0 && i < method_count, "index out of bounds");
3441   return true;
3442 }
3443 
3444 #endif //PRODUCT
3445 
3446 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
3447   st->print("a ");
3448   name()->print_value_on(st);
3449   obj->print_address_on(st);
3450   if (this == SystemDictionary::String_klass()
3451       && java_lang_String::value(obj) != NULL) {
3452     ResourceMark rm;
3453     int len = java_lang_String::length(obj);
3454     int plen = (len < 24 ? len : 12);
3455     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
3456     st->print(" = \"%s\"", str);
3457     if (len > plen)
3458       st->print("...[%d]", len);
3459   } else if (this == SystemDictionary::Class_klass()) {
3460     Klass* k = java_lang_Class::as_Klass(obj);
3461     st->print(" = ");
3462     if (k != NULL) {
3463       k->print_value_on(st);
3464     } else {
3465       const char* tname = type2name(java_lang_Class::primitive_type(obj));
3466       st->print("%s", tname ? tname : "type?");
3467     }
3468   } else if (this == SystemDictionary::MethodType_klass()) {
3469     st->print(" = ");
3470     java_lang_invoke_MethodType::print_signature(obj, st);
3471   } else if (java_lang_boxing_object::is_instance(obj)) {
3472     st->print(" = ");
3473     java_lang_boxing_object::print(obj, st);
3474   } else if (this == SystemDictionary::LambdaForm_klass()) {
3475     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
3476     if (vmentry != NULL) {
3477       st->print(" => ");
3478       vmentry->print_value_on(st);
3479     }
3480   } else if (this == SystemDictionary::MemberName_klass()) {
3481     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
3482     if (vmtarget != NULL) {
3483       st->print(" = ");
3484       vmtarget->print_value_on(st);
3485     } else {
3486       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
3487       st->print(".");
3488       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
3489     }
3490   }
3491 }
3492 
3493 const char* InstanceKlass::internal_name() const {
3494   return external_name();
3495 }
3496 
3497 void InstanceKlass::print_class_load_logging(ClassLoaderData* loader_data,
3498                                              const char* module_name,
3499                                              const ClassFileStream* cfs) const {
3500   if (!log_is_enabled(Info, class, load)) {
3501     return;
3502   }
3503 
3504   ResourceMark rm;
3505   LogMessage(class, load) msg;
3506   stringStream info_stream;
3507 
3508   // Name and class hierarchy info
3509   info_stream.print("%s", external_name());
3510 
3511   // Source
3512   if (cfs != NULL) {
3513     if (cfs->source() != NULL) {
3514       if (module_name != NULL) {
3515         if (ClassLoader::is_modules_image(cfs->source())) {
3516           info_stream.print(" source: jrt:/%s", module_name);
3517         } else {
3518           info_stream.print(" source: %s", cfs->source());
3519         }
3520       } else {
3521         info_stream.print(" source: %s", cfs->source());
3522       }
3523     } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) {
3524       Thread* THREAD = Thread::current();
3525       Klass* caller =
3526             THREAD->is_Java_thread()
3527                 ? ((JavaThread*)THREAD)->security_get_caller_class(1)
3528                 : NULL;
3529       // caller can be NULL, for example, during a JVMTI VM_Init hook
3530       if (caller != NULL) {
3531         info_stream.print(" source: instance of %s", caller->external_name());
3532       } else {
3533         // source is unknown
3534       }
3535     } else {
3536       oop class_loader = loader_data->class_loader();
3537       info_stream.print(" source: %s", class_loader->klass()->external_name());
3538     }
3539   } else {
3540     info_stream.print(" source: shared objects file");
3541   }
3542 
3543   msg.info("%s", info_stream.as_string());
3544 
3545   if (log_is_enabled(Debug, class, load)) {
3546     stringStream debug_stream;
3547 
3548     // Class hierarchy info
3549     debug_stream.print(" klass: " INTPTR_FORMAT " super: " INTPTR_FORMAT,
3550                        p2i(this),  p2i(superklass()));
3551 
3552     // Interfaces
3553     if (local_interfaces() != NULL && local_interfaces()->length() > 0) {
3554       debug_stream.print(" interfaces:");
3555       int length = local_interfaces()->length();
3556       for (int i = 0; i < length; i++) {
3557         debug_stream.print(" " INTPTR_FORMAT,
3558                            p2i(InstanceKlass::cast(local_interfaces()->at(i))));
3559       }
3560     }
3561 
3562     // Class loader
3563     debug_stream.print(" loader: [");
3564     loader_data->print_value_on(&debug_stream);
3565     debug_stream.print("]");
3566 
3567     // Classfile checksum
3568     if (cfs) {
3569       debug_stream.print(" bytes: %d checksum: %08x",
3570                          cfs->length(),
3571                          ClassLoader::crc32(0, (const char*)cfs->buffer(),
3572                          cfs->length()));
3573     }
3574 
3575     msg.debug("%s", debug_stream.as_string());
3576   }
3577 }
3578 
3579 #if INCLUDE_SERVICES
3580 // Size Statistics
3581 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
3582   Klass::collect_statistics(sz);
3583 
3584   sz->_inst_size  = wordSize * size_helper();
3585   sz->_vtab_bytes = wordSize * vtable_length();
3586   sz->_itab_bytes = wordSize * itable_length();
3587   sz->_nonstatic_oopmap_bytes = wordSize * nonstatic_oop_map_size();
3588 
3589   int n = 0;
3590   n += (sz->_methods_array_bytes         = sz->count_array(methods()));
3591   n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
3592   n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
3593   n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
3594   n += (sz->_fields_bytes                = sz->count_array(fields()));
3595   n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
3596   n += (sz->_nest_members_bytes          = sz->count_array(nest_members()));
3597   sz->_ro_bytes += n;
3598 
3599   const ConstantPool* cp = constants();
3600   if (cp) {
3601     cp->collect_statistics(sz);
3602   }
3603 
3604   const Annotations* anno = annotations();
3605   if (anno) {
3606     anno->collect_statistics(sz);
3607   }
3608 
3609   const Array<Method*>* methods_array = methods();
3610   if (methods()) {
3611     for (int i = 0; i < methods_array->length(); i++) {
3612       Method* method = methods_array->at(i);
3613       if (method) {
3614         sz->_method_count ++;
3615         method->collect_statistics(sz);
3616       }
3617     }
3618   }
3619 }
3620 #endif // INCLUDE_SERVICES
3621 
3622 // Verification
3623 
3624 class VerifyFieldClosure: public BasicOopIterateClosure {
3625  protected:
3626   template <class T> void do_oop_work(T* p) {
3627     oop obj = RawAccess<>::oop_load(p);
3628     if (!oopDesc::is_oop_or_null(obj)) {
3629       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj));
3630       Universe::print_on(tty);
3631       guarantee(false, "boom");
3632     }
3633   }
3634  public:
3635   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
3636   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
3637 };
3638 
3639 void InstanceKlass::verify_on(outputStream* st) {
3640 #ifndef PRODUCT
3641   // Avoid redundant verifies, this really should be in product.
3642   if (_verify_count == Universe::verify_count()) return;
3643   _verify_count = Universe::verify_count();
3644 #endif
3645 
3646   // Verify Klass
3647   Klass::verify_on(st);
3648 
3649   // Verify that klass is present in ClassLoaderData
3650   guarantee(class_loader_data()->contains_klass(this),
3651             "this class isn't found in class loader data");
3652 
3653   // Verify vtables
3654   if (is_linked()) {
3655     // $$$ This used to be done only for m/s collections.  Doing it
3656     // always seemed a valid generalization.  (DLD -- 6/00)
3657     vtable().verify(st);
3658   }
3659 
3660   // Verify first subklass
3661   if (subklass() != NULL) {
3662     guarantee(subklass()->is_klass(), "should be klass");
3663   }
3664 
3665   // Verify siblings
3666   Klass* super = this->super();
3667   Klass* sib = next_sibling();
3668   if (sib != NULL) {
3669     if (sib == this) {
3670       fatal("subclass points to itself " PTR_FORMAT, p2i(sib));
3671     }
3672 
3673     guarantee(sib->is_klass(), "should be klass");
3674     guarantee(sib->super() == super, "siblings should have same superklass");
3675   }
3676 
3677   // Verify local interfaces
3678   if (local_interfaces()) {
3679     Array<InstanceKlass*>* local_interfaces = this->local_interfaces();
3680     for (int j = 0; j < local_interfaces->length(); j++) {
3681       InstanceKlass* e = local_interfaces->at(j);
3682       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
3683     }
3684   }
3685 
3686   // Verify transitive interfaces
3687   if (transitive_interfaces() != NULL) {
3688     Array<InstanceKlass*>* transitive_interfaces = this->transitive_interfaces();
3689     for (int j = 0; j < transitive_interfaces->length(); j++) {
3690       InstanceKlass* e = transitive_interfaces->at(j);
3691       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
3692     }
3693   }
3694 
3695   // Verify methods
3696   if (methods() != NULL) {
3697     Array<Method*>* methods = this->methods();
3698     for (int j = 0; j < methods->length(); j++) {
3699       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3700     }
3701     for (int j = 0; j < methods->length() - 1; j++) {
3702       Method* m1 = methods->at(j);
3703       Method* m2 = methods->at(j + 1);
3704       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3705     }
3706   }
3707 
3708   // Verify method ordering
3709   if (method_ordering() != NULL) {
3710     Array<int>* method_ordering = this->method_ordering();
3711     int length = method_ordering->length();
3712     if (JvmtiExport::can_maintain_original_method_order() ||
3713         ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
3714       guarantee(length == methods()->length(), "invalid method ordering length");
3715       jlong sum = 0;
3716       for (int j = 0; j < length; j++) {
3717         int original_index = method_ordering->at(j);
3718         guarantee(original_index >= 0, "invalid method ordering index");
3719         guarantee(original_index < length, "invalid method ordering index");
3720         sum += original_index;
3721       }
3722       // Verify sum of indices 0,1,...,length-1
3723       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
3724     } else {
3725       guarantee(length == 0, "invalid method ordering length");
3726     }
3727   }
3728 
3729   // Verify default methods
3730   if (default_methods() != NULL) {
3731     Array<Method*>* methods = this->default_methods();
3732     for (int j = 0; j < methods->length(); j++) {
3733       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3734     }
3735     for (int j = 0; j < methods->length() - 1; j++) {
3736       Method* m1 = methods->at(j);
3737       Method* m2 = methods->at(j + 1);
3738       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3739     }
3740   }
3741 
3742   // Verify JNI static field identifiers
3743   if (jni_ids() != NULL) {
3744     jni_ids()->verify(this);
3745   }
3746 
3747   // Verify other fields
3748   if (array_klasses() != NULL) {
3749     guarantee(array_klasses()->is_klass(), "should be klass");
3750   }
3751   if (constants() != NULL) {
3752     guarantee(constants()->is_constantPool(), "should be constant pool");
3753   }
3754   const Klass* anonymous_host = unsafe_anonymous_host();
3755   if (anonymous_host != NULL) {
3756     guarantee(anonymous_host->is_klass(), "should be klass");
3757   }
3758 }
3759 
3760 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
3761   Klass::oop_verify_on(obj, st);
3762   VerifyFieldClosure blk;
3763   obj->oop_iterate(&blk);
3764 }
3765 
3766 
3767 // JNIid class for jfieldIDs only
3768 // Note to reviewers:
3769 // These JNI functions are just moved over to column 1 and not changed
3770 // in the compressed oops workspace.
3771 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
3772   _holder = holder;
3773   _offset = offset;
3774   _next = next;
3775   debug_only(_is_static_field_id = false;)
3776 }
3777 
3778 
3779 JNIid* JNIid::find(int offset) {
3780   JNIid* current = this;
3781   while (current != NULL) {
3782     if (current->offset() == offset) return current;
3783     current = current->next();
3784   }
3785   return NULL;
3786 }
3787 
3788 void JNIid::deallocate(JNIid* current) {
3789   while (current != NULL) {
3790     JNIid* next = current->next();
3791     delete current;
3792     current = next;
3793   }
3794 }
3795 
3796 
3797 void JNIid::verify(Klass* holder) {
3798   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
3799   int end_field_offset;
3800   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
3801 
3802   JNIid* current = this;
3803   while (current != NULL) {
3804     guarantee(current->holder() == holder, "Invalid klass in JNIid");
3805 #ifdef ASSERT
3806     int o = current->offset();
3807     if (current->is_static_field_id()) {
3808       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
3809     }
3810 #endif
3811     current = current->next();
3812   }
3813 }
3814 
3815 void InstanceKlass::set_init_state(ClassState state) {
3816 #ifdef ASSERT
3817   bool good_state = is_shared() ? (_init_state <= state)
3818                                                : (_init_state < state);
3819   assert(good_state || state == allocated, "illegal state transition");
3820 #endif
3821   _init_state = (u1)state;
3822 }
3823 
3824 #if INCLUDE_JVMTI
3825 
3826 // RedefineClasses() support for previous versions
3827 
3828 // Globally, there is at least one previous version of a class to walk
3829 // during class unloading, which is saved because old methods in the class
3830 // are still running.   Otherwise the previous version list is cleaned up.
3831 bool InstanceKlass::_has_previous_versions = false;
3832 
3833 // Returns true if there are previous versions of a class for class
3834 // unloading only. Also resets the flag to false. purge_previous_version
3835 // will set the flag to true if there are any left, i.e., if there's any
3836 // work to do for next time. This is to avoid the expensive code cache
3837 // walk in CLDG::clean_deallocate_lists().
3838 bool InstanceKlass::has_previous_versions_and_reset() {
3839   bool ret = _has_previous_versions;
3840   log_trace(redefine, class, iklass, purge)("Class unloading: has_previous_versions = %s",
3841      ret ? "true" : "false");
3842   _has_previous_versions = false;
3843   return ret;
3844 }
3845 
3846 // Purge previous versions before adding new previous versions of the class and
3847 // during class unloading.
3848 void InstanceKlass::purge_previous_version_list() {
3849   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
3850   assert(has_been_redefined(), "Should only be called for main class");
3851 
3852   // Quick exit.
3853   if (previous_versions() == NULL) {
3854     return;
3855   }
3856 
3857   // This klass has previous versions so see what we can cleanup
3858   // while it is safe to do so.
3859 
3860   int deleted_count = 0;    // leave debugging breadcrumbs
3861   int live_count = 0;
3862   ClassLoaderData* loader_data = class_loader_data();
3863   assert(loader_data != NULL, "should never be null");
3864 
3865   ResourceMark rm;
3866   log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name());
3867 
3868   // previous versions are linked together through the InstanceKlass
3869   InstanceKlass* pv_node = previous_versions();
3870   InstanceKlass* last = this;
3871   int version = 0;
3872 
3873   // check the previous versions list
3874   for (; pv_node != NULL; ) {
3875 
3876     ConstantPool* pvcp = pv_node->constants();
3877     assert(pvcp != NULL, "cp ref was unexpectedly cleared");
3878 
3879     if (!pvcp->on_stack()) {
3880       // If the constant pool isn't on stack, none of the methods
3881       // are executing.  Unlink this previous_version.
3882       // The previous version InstanceKlass is on the ClassLoaderData deallocate list
3883       // so will be deallocated during the next phase of class unloading.
3884       log_trace(redefine, class, iklass, purge)
3885         ("previous version " INTPTR_FORMAT " is dead.", p2i(pv_node));
3886       // For debugging purposes.
3887       pv_node->set_is_scratch_class();
3888       // Unlink from previous version list.
3889       assert(pv_node->class_loader_data() == loader_data, "wrong loader_data");
3890       InstanceKlass* next = pv_node->previous_versions();
3891       pv_node->link_previous_versions(NULL);   // point next to NULL
3892       last->link_previous_versions(next);
3893       // Add to the deallocate list after unlinking
3894       loader_data->add_to_deallocate_list(pv_node);
3895       pv_node = next;
3896       deleted_count++;
3897       version++;
3898       continue;
3899     } else {
3900       log_trace(redefine, class, iklass, purge)("previous version " INTPTR_FORMAT " is alive", p2i(pv_node));
3901       assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
3902       guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
3903       live_count++;
3904       // found a previous version for next time we do class unloading
3905       _has_previous_versions = true;
3906     }
3907 
3908     // At least one method is live in this previous version.
3909     // Reset dead EMCP methods not to get breakpoints.
3910     // All methods are deallocated when all of the methods for this class are no
3911     // longer running.
3912     Array<Method*>* method_refs = pv_node->methods();
3913     if (method_refs != NULL) {
3914       log_trace(redefine, class, iklass, purge)("previous methods length=%d", method_refs->length());
3915       for (int j = 0; j < method_refs->length(); j++) {
3916         Method* method = method_refs->at(j);
3917 
3918         if (!method->on_stack()) {
3919           // no breakpoints for non-running methods
3920           if (method->is_running_emcp()) {
3921             method->set_running_emcp(false);
3922           }
3923         } else {
3924           assert (method->is_obsolete() || method->is_running_emcp(),
3925                   "emcp method cannot run after emcp bit is cleared");
3926           log_trace(redefine, class, iklass, purge)
3927             ("purge: %s(%s): prev method @%d in version @%d is alive",
3928              method->name()->as_C_string(), method->signature()->as_C_string(), j, version);
3929         }
3930       }
3931     }
3932     // next previous version
3933     last = pv_node;
3934     pv_node = pv_node->previous_versions();
3935     version++;
3936   }
3937   log_trace(redefine, class, iklass, purge)
3938     ("previous version stats: live=%d, deleted=%d", live_count, deleted_count);
3939 }
3940 
3941 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,
3942                                                 int emcp_method_count) {
3943   int obsolete_method_count = old_methods->length() - emcp_method_count;
3944 
3945   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
3946       _previous_versions != NULL) {
3947     // We have a mix of obsolete and EMCP methods so we have to
3948     // clear out any matching EMCP method entries the hard way.
3949     int local_count = 0;
3950     for (int i = 0; i < old_methods->length(); i++) {
3951       Method* old_method = old_methods->at(i);
3952       if (old_method->is_obsolete()) {
3953         // only obsolete methods are interesting
3954         Symbol* m_name = old_method->name();
3955         Symbol* m_signature = old_method->signature();
3956 
3957         // previous versions are linked together through the InstanceKlass
3958         int j = 0;
3959         for (InstanceKlass* prev_version = _previous_versions;
3960              prev_version != NULL;
3961              prev_version = prev_version->previous_versions(), j++) {
3962 
3963           Array<Method*>* method_refs = prev_version->methods();
3964           for (int k = 0; k < method_refs->length(); k++) {
3965             Method* method = method_refs->at(k);
3966 
3967             if (!method->is_obsolete() &&
3968                 method->name() == m_name &&
3969                 method->signature() == m_signature) {
3970               // The current RedefineClasses() call has made all EMCP
3971               // versions of this method obsolete so mark it as obsolete
3972               log_trace(redefine, class, iklass, add)
3973                 ("%s(%s): flush obsolete method @%d in version @%d",
3974                  m_name->as_C_string(), m_signature->as_C_string(), k, j);
3975 
3976               method->set_is_obsolete();
3977               break;
3978             }
3979           }
3980 
3981           // The previous loop may not find a matching EMCP method, but
3982           // that doesn't mean that we can optimize and not go any
3983           // further back in the PreviousVersion generations. The EMCP
3984           // method for this generation could have already been made obsolete,
3985           // but there still may be an older EMCP method that has not
3986           // been made obsolete.
3987         }
3988 
3989         if (++local_count >= obsolete_method_count) {
3990           // no more obsolete methods so bail out now
3991           break;
3992         }
3993       }
3994     }
3995   }
3996 }
3997 
3998 // Save the scratch_class as the previous version if any of the methods are running.
3999 // The previous_versions are used to set breakpoints in EMCP methods and they are
4000 // also used to clean MethodData links to redefined methods that are no longer running.
4001 void InstanceKlass::add_previous_version(InstanceKlass* scratch_class,
4002                                          int emcp_method_count) {
4003   assert(Thread::current()->is_VM_thread(),
4004          "only VMThread can add previous versions");
4005 
4006   ResourceMark rm;
4007   log_trace(redefine, class, iklass, add)
4008     ("adding previous version ref for %s, EMCP_cnt=%d", scratch_class->external_name(), emcp_method_count);
4009 
4010   // Clean out old previous versions for this class
4011   purge_previous_version_list();
4012 
4013   // Mark newly obsolete methods in remaining previous versions.  An EMCP method from
4014   // a previous redefinition may be made obsolete by this redefinition.
4015   Array<Method*>* old_methods = scratch_class->methods();
4016   mark_newly_obsolete_methods(old_methods, emcp_method_count);
4017 
4018   // If the constant pool for this previous version of the class
4019   // is not marked as being on the stack, then none of the methods
4020   // in this previous version of the class are on the stack so
4021   // we don't need to add this as a previous version.
4022   ConstantPool* cp_ref = scratch_class->constants();
4023   if (!cp_ref->on_stack()) {
4024     log_trace(redefine, class, iklass, add)("scratch class not added; no methods are running");
4025     // For debugging purposes.
4026     scratch_class->set_is_scratch_class();
4027     scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class);
4028     return;
4029   }
4030 
4031   if (emcp_method_count != 0) {
4032     // At least one method is still running, check for EMCP methods
4033     for (int i = 0; i < old_methods->length(); i++) {
4034       Method* old_method = old_methods->at(i);
4035       if (!old_method->is_obsolete() && old_method->on_stack()) {
4036         // if EMCP method (not obsolete) is on the stack, mark as EMCP so that
4037         // we can add breakpoints for it.
4038 
4039         // We set the method->on_stack bit during safepoints for class redefinition
4040         // and use this bit to set the is_running_emcp bit.
4041         // After the safepoint, the on_stack bit is cleared and the running emcp
4042         // method may exit.   If so, we would set a breakpoint in a method that
4043         // is never reached, but this won't be noticeable to the programmer.
4044         old_method->set_running_emcp(true);
4045         log_trace(redefine, class, iklass, add)
4046           ("EMCP method %s is on_stack " INTPTR_FORMAT, old_method->name_and_sig_as_C_string(), p2i(old_method));
4047       } else if (!old_method->is_obsolete()) {
4048         log_trace(redefine, class, iklass, add)
4049           ("EMCP method %s is NOT on_stack " INTPTR_FORMAT, old_method->name_and_sig_as_C_string(), p2i(old_method));
4050       }
4051     }
4052   }
4053 
4054   // Add previous version if any methods are still running.
4055   // Set has_previous_version flag for processing during class unloading.
4056   _has_previous_versions = true;
4057   log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack.");
4058   assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");
4059   scratch_class->link_previous_versions(previous_versions());
4060   link_previous_versions(scratch_class);
4061 } // end add_previous_version()
4062 
4063 #endif // INCLUDE_JVMTI
4064 
4065 Method* InstanceKlass::method_with_idnum(int idnum) {
4066   Method* m = NULL;
4067   if (idnum < methods()->length()) {
4068     m = methods()->at(idnum);
4069   }
4070   if (m == NULL || m->method_idnum() != idnum) {
4071     for (int index = 0; index < methods()->length(); ++index) {
4072       m = methods()->at(index);
4073       if (m->method_idnum() == idnum) {
4074         return m;
4075       }
4076     }
4077     // None found, return null for the caller to handle.
4078     return NULL;
4079   }
4080   return m;
4081 }
4082 
4083 
4084 Method* InstanceKlass::method_with_orig_idnum(int idnum) {
4085   if (idnum >= methods()->length()) {
4086     return NULL;
4087   }
4088   Method* m = methods()->at(idnum);
4089   if (m != NULL && m->orig_method_idnum() == idnum) {
4090     return m;
4091   }
4092   // Obsolete method idnum does not match the original idnum
4093   for (int index = 0; index < methods()->length(); ++index) {
4094     m = methods()->at(index);
4095     if (m->orig_method_idnum() == idnum) {
4096       return m;
4097     }
4098   }
4099   // None found, return null for the caller to handle.
4100   return NULL;
4101 }
4102 
4103 
4104 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {
4105   InstanceKlass* holder = get_klass_version(version);
4106   if (holder == NULL) {
4107     return NULL; // The version of klass is gone, no method is found
4108   }
4109   Method* method = holder->method_with_orig_idnum(idnum);
4110   return method;
4111 }
4112 
4113 #if INCLUDE_JVMTI
4114 JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() {
4115   return _cached_class_file;
4116 }
4117 
4118 jint InstanceKlass::get_cached_class_file_len() {
4119   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
4120 }
4121 
4122 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
4123   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
4124 }
4125 #endif
4126 
4127 #define THROW_DVT_ERROR(s) \
4128   Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_IncompatibleClassChangeError(), \
4129       "ValueCapableClass class '%s' %s", external_name(),(s)); \
4130       return