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